PDF Generator In Java (Without Losing Formatting)
Tags: ironpdf, java, maven, programming
Published: 2023-02-06 06:14:11

In this tutorial, we will learn to create a pdf generator in Java. We will create a pdf generator to generate pdf documents from text, URL, and HTML pages. We will also learn to create password-protected pdf files.

We need a pdf generator in our application to generate and print invoices, reports, and pdf forms. Pdf documents are widely used, therefore, it is necessary for a developer to learn about generating pdf documents in Java.

We need a third-party pdf library for generating a pdf file. There are numerous pdf libraries are available, but finding the best is a difficult job. Some libraries are paid, some are difficult to use, some have limited features and some have performance issues.

IronPDF is a Java library that is free for development, easy to use, and provides all features which allow us to create pdf files, read pdf files, generate a password-protected pdf file, digitally sign pdf files, edit existing pdf, and many more. In this tutorial, we will use IronPDF to develop our pdf generator.
##IronPDF:

[IronPDF](https://ironpdf.com/java/) is a java Library that is used to create, read, and manipulate pdf documents, It has 50+ features. It supports all JDK versions 8+, scala, and kotlin. It can work well with all application types such as desktop, mobile, and web. It's very easy to use as we can generate and read pdf files with just 1 line of code. We can integrate pdf functionalities into our application with high performance and efficiency.

Now, Let us start developing our pdf generator in Java.

First of all, we need to create a new java project.
##Create a Java Project:

I am using IntelliJ IDE for this tutorial, you can use any as per your preference. Steps for creating a new project may differ from IDE to IDE.

Open your IntelliJ IDE. Click on File > New > Project. The following window will appear.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3e9eikblglhgtobpxhpz.png)
Enter Project Name, Select Location, Language, Build System, and JDK. Press on Create Button to Create a new project.

Now, we need to install the IronPDF java pdf library to integrate pdf functionalities into our application.

##Install IronPDF:

Open the pom.xml file of your project. Write the following XML under the properties tag.

```
<dependencies>
    <dependency>
        <groupId>com.ironsoftware</groupId>
        <artifactId>ironpdf</artifactId>
        <version>2022.11.0</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-simple</artifactId>
        <version>2.0.3</version>
    </dependency>
</dependencies> 
```
This will install [IronPDF](https://search.maven.org/artifact/com.ironsoftware/ironpdf-engine-windows-x86) from the [maven repository](https://search.maven.org/search?q=a:ironpdf-engine-windows-x86).

Save the XML file, build, and run the project. This will install the IronPDF library in our project, to make it ready to use.

##Generate a Pdf File from Plain Text:

Let's write a code to generate a pdf file from the string. The following sample code demonstrates the example.

```
PdfDocument myPdf = PdfDocument.renderHtmlAsPdf("This is my First PDF generated by PDF Generator.");
// Save the PdfDocument to a file
        try {
            myPdf.saveAs(Paths.get("PDFGenerator.pdf") );
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
```
The rederHTMLAsPdf() function takes a string as a parameter and returns the pdf document instance to generate a new document. The saveAs() function is provided by PdfDocument class takes a path as a parameter and save the newly generated pdf file into the directory.

###Output:

Following is the generated pdf document by our program.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/14dlli5iiowcix10wlfv.png)
##Generate pdf documents from URL:

Iron PDF makes Creating pdf files from the URL very easy. We can create a pdf file from a URL with just a single line of code as shown below:
```
PdfDocument myPdf = PdfDocument.renderUrlAsPdf("https://edu.gcfglobal.org/en/basic-computer-skills/what-is-a-pdf-file/1/");
// Save the PdfDocument to a file
        try {
            myPdf.saveAs(Paths.get("PDFGenerator.pdf") );
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
```
The renderUrlAsPdf() function tasks the URL as a parameter and returns the pdf document instance of the provided URL. The saveAs() function takes the path as a parameter and saves the document in the provided directory.

###Output:

The following is the output generated by our program.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7c1p4kcbokn0f0279bvd.png)
We can see that our program has generated a pdf file with 100% accuracy. It keeps the same design and format while generating a pdf document.

##Generate Pdf files from HTML:

IronPDf also provides the functionality of generating pdf documents from HTML. We can use all HTML tags in combination with CSS for adding image files, styling, and formatting our pdf document. We can do it with just a single line of code.

```
String htmlContent = "<html>\n" +
                "<head>\n" +
                "<style>\n" +
                "body {\n" +
                "  color: blue;\n" +
                "}\n" +
                "\n" +
                "h1 {\n" +
                "  color: green;\n" +
                "}\n" +
                "</style>\n" +
                "</head>\n" +
                "<body>\n" +
                "\n" +
                "<h1>This is PDF Generator in Java</h1>\n" +
                "<p>This document is generated by our PDF Generator</p>\n" +
                "\n" +
                "</body>\n" +
                "</html>";
        PdfDocument myPdf = PdfDocument.renderHtmlAsPdf(htmlContent);
// Save the PdfDocument to a file
        try {
            myPdf.saveAs(Paths.get("PDFGenerator.pdf") );
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
```
I have used a variable htmlContent to assign our HTML text. I have then passed this variable in the renderHtmlAsPdf() function to generate a pdf file.

###Output:

The following is the output generated by our pdf generator. It has kept the same styling and formatting that we have defined in our HTML content.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hph6bt9an75iqcvv3fia.png)
We can also create a new HTML file to keep our code neat and clean. We can add content to our HTML File, and add styling with any of the three CSS styling methods such as in-line, internal, and external.

##Generate pdf document from HTML File:

In this example, I will use In-line styling to make this tutorial simple. You can use any of your choices.

I have put the same HTML content as used in the above example in my HTML file as shown below:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nmk4rl1a8y7p072q0bvo.png)
Now, Let's write a code to create a pdf file from the HMTL file.

```
PdfDocument myPdf = PdfDocument.renderHtmlFileAsPdf("myFile.html");
// Save the PdfDocument to a file
        try {
            myPdf.saveAs(Paths.get("PDFGenerator.pdf") );
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
```
The renderHtmlFileAsPdf() function takes the path of the HTML file and converts that into the pdf document. We can then save the pdf document using the saveAs() function.

try and cath is used to catch exceptions.

###Output:

Following is the output generated by our program.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9a4mv4h7mfy3xdddltzc.png)
We can observe that it's 100% similar to our HTML file.

There are multiple features that we can add to our pdf files which include:

1. Add Header and Footer
2. Add Background and foreground to pdf
3. Append pdf
4. Remove Pages
5. Add Title Page
6. Add Watermark
7. Add Stamp
8. Extract Images and many more.

There are many more, which I cannot cover in a single article. Please click [here](https://ironpdf.com/java/tutorials/html-to-pdf/) for more details.

##Summary:

In this tutorial, we have learned to create our own pdf generator in Java. We have followed the following steps:

1. Create a New Project
2. Install IronPDF Library
3. Generate PDF from TEXT
4. Generate PDF from URL
5. Generate PDF from HTML String
6. Generate PDF from HTML File

We have generated each pdf with just a single line of code with 100% accuracy.

There are other multiple useful features provided by IronPDF that we can use, as there is a limited scope of this article, so I can not mention all of the here, But I will suggest you visit their [official documentation](https://ironpdf.com/java/examples/using-html-to-create-a-pdf/), and spend a few minutes exploring all amazing functionalities.

IronPDF is free for development, which adds its watermark to every generated pdf file. You can purchase its [commercial license](https://ironpdf.com/java/licensing/) to remove the watermark and deploy your application in any environment. You can also get a [30-day free trial](https://ironpdf.com/java/#trial-license) without entering any credit or debit card details.

I have kept this tutorial simple so that both the expert and beginners can benefit from it. If you have any suggestions or queries, feel free to ask in the comment section.