Java PDF Generator (Code Example Tutorial)

PDF, or Portable Document Format, is a digital document which is used to save and send data over internet. Generating new PDF documents in the Java programming language allows developers to automate the data saving process in their Java applications. Whether it is a report, an invoice or even a form, PDF helps to preserve the structure and formatting of content.

In this article, we will see how to use IronPDF to generate new file, extract content and save PDFs.

IronPDF for Java

IronPDF for Java is built for generating PDF documents or PDF form from HTML code whether from file, HTML string, HTML pages or URL. It generates PDF files with accuracy and formatting is also preserved. It is designed in a way that developers find it easy to use.

IronPDF is built on top of the .NET Framework, allowing it to be a versatile tool for generating PDFs in various contexts.

IronPDF provides the following functions for generating and manipulating large documents:

  1. The ability to add and extract content from PDFs (text, images, tables, etc.)
  2. The ability to control the layout and formatting of the document (e.g, set fonts, colors, margins...)
  3. The ability to complete forms and add digital signatures

Steps to Create a PDF File in a Java Application

Prerequisites

To use IronPDF to create a PDF generating tool, we need the following software installed on the computer:

  1. Java Development Kit - JDK is required for building and running Java programs. If it is not installed, download the latest release from Oracle Website.
  2. Integrated Development Environment - IDE is software which helps write, edit and debug a program. Download any IDE for Java. E.g. Eclipse, Netbeans, Intellij.
  3. Maven - Maven is an automation and open source Java tool which helps downloading libraries from Central Maven Repository. Download it from the Apache Maven website.
  4. IronPDF - Finally, IronPDF is required to create PDF files in Java. This needs to be added as a dependency in your Java Maven Project. Include the IronPDF artifact along with slf4j dependency in the pom.xml file as shown below:

    <dependency>
       <groupId>com.ironsoftware</groupId>
       <artifactId>com.ironsoftware</artifactId>
       <version>2024.3.1</version>
    </dependency>
    XML

Adding Necessary Imports

First of all add the following line on top of the Java main class source code file, to import all the required important class methods from IronPDF library.

import com.ironsoftware.ironpdf.*;
JAVA

Next, configure IronPDF with a valid license key to use its methods. Invoke setLicenseKey method in main method.

License.setLicenseKey("Your license key");
JAVA

Note: You can get a free trial license key to create and read PDFs.

Generate PDF Documents from HTML String

Creating PDF files from HTML string is very easy and it usually takes one or two lines of code to do it. Here, an HTML code is written as a string in a variable and then passed to renderHtmlAsPdf method found in PdfDocument class. The following code generates a new PDF document instance:

String htmlString = "<h1>Hello World!</h1><p>This is an example of HTML string in Java.</p>";
PdfDocument pdf = PdfDocument.renderHtmlAsPdf(htmlString);
JAVA

Now, use the saveAs method to save the generated PDF to a path on your local system:

pdf.saveAs(Paths.get("htmlstring.pdf"));
JAVA

The above line of code creates a PDF called "htmlstring.pdf" containing the HTML string's contents.

The output is as follows:

Java PDF Generator Tutorial - Figure 1: HTML String to PDF Output

Output from the renderHtmlAsPdf method. The string of HTML is converted into a functional PDF document

Create PDF Documents from HTML Files

The following code creates a PDF file from an HTML file:

PdfDocument myPdf = PdfDocument.renderHtmlFileAsPdf("example.html");
myPdf.saveAs(Paths.get("html_file.pdf"));
JAVA

HTML file code:

<html>
    <head>
        <title>Example HTML File</title>
    </head>
    <body>
        <h1>HTML File Example</h1>
        <p style="font-style:Italic;">This is an example HTML file</p>
    </body>
</html>
<html>
    <head>
        <title>Example HTML File</title>
    </head>
    <body>
        <h1>HTML File Example</h1>
        <p style="font-style:Italic;">This is an example HTML file</p>
    </body>
</html>
HTML

In the above code, the renderHtmlFileAsPdf method generates PDF files from HTML files. This method accepts a string argument containing the path to the HTML file.

IronPDF renders the HTML file elements along with the CSS and JavaScript attached to it if any. You can see in the output below that the CSS styling is also maintained by IronPDF and the output is same as it would have been in web browser.

Java PDF Generator Tutorial - Figure 2: HTML File to PDF Output

Output from the renderHtmlFileAsPdf method with an example HTML file stored on the local disk.

Generate PDF Files from URL

The renderUrlAsPdf method is used to create PDF files from a web page. It accepts the web page's URL as an argument.

PdfDocument urlToPdf = PdfDocument.renderUrlAsPdf("https://ironpdf.com");
urlToPdf.saveAs(Paths.get("urlToPdf.pdf"));
JAVA
Java PDF Generator Tutorial - Figure 3: URL to PDF Output

Output from the renderUrlAsPdf. The method generates a pixel perfect PDF version of the IronPDF homepage.

Additional rendering options can be set to configure PDF generation. You can get more information on URL to PDF Code Example page.

Generating Password Protected PDF Files

IronPDF can be used to create password protected PDF file with SecurityOptions class. All file permissions can be set if you integrate PDF functionalities of IronPDF. The code goes as follows:

SecurityOptions securityOptions = new SecurityOptions();
securityOptions.setUserPassword("shareable");
JAVA

setUserPassword is used to set a secure password. The below code sample applies password protection to the PDF document that we created in the URL to PDF example:

SecurityManager securityManager =  urlToPdf.getSecurity();
securityManager.setSecurityOptions(securityOptions);
urlToPdf.saveAs("protected.pdf");
JAVA

The PDF file is now password protected. Now open the PDF file and a password option will appear:

Java PDF Generator Tutorial - Figure 4: Password Protected File

The generated PDF document with Password Protection enabled

After entering the password correctly, the PDF document will open.

Java PDF Generator Tutorial - Figure 5: PDF document

More security settings and metadata about the PDF files can be explored in the related code example.

Summary

In this article, we explored the IronPDF library to create PDFs from multiple methods. IronPDF is a pure Java library and powerfully built to easily work with PDF files in Java.

IronPDF's Engine makes it easy to create PDFs from HTML files, Image files, XML documents, Jasper reports or any other sources. It complies with standard Java printing API which helps print documents with ease and you can also digitally sign PDF files. IronPDF helps to get all the PDF related tasks done quickly and easily.

IronPDF is not an open source Java library. It provides a commercial license which starts from $749. You can also get a free trial to test it in production within your Java applications.