How to Create PDF Files in Java

Creating PDFs programmatically using Java allows developers to automate the creation of PDF documents as part of their applications. This can be useful in various situations, such as generating invoices, reports, or other types of new PDF documents on demand.

This How-To Guide covers the usage of the IronPDF in creating PDF files programmatically in Java applications.

IronPDF Java PDF Library

IronPDF is a Java library for creating PDF documents from HTML. It is designed to be easy to use. It provides functions for creating and customizing PDFs, including:

  1. The ability to add text, images, and other types of content
  2. The ability to choose fonts and colors, and control the layout and formatting of the document

IronPDF is built on top of the .NET Framework, allowing it to be used in both .NET and Java applications. This makes it a versatile tool for creating PDFs in various contexts.

In addition to its core PDF generation capabilities, IronPDF also supports other PDF-related tasks. These include conversion between other file formats, extraction of text and data from PDFs, and securing PDFs with password encryption.

Steps to Create PDF Document in a Java Application

Prerequisites

To use IronPDF to create PDFs in a Maven project, please ensure that the computer has the following prerequisite software installed:

  1. Java Development Kit (JDK): A JDK is required for compiling and running Java applications. Please download the JDK from the Oracle website.
  2. Maven: Maven is required for downloading project libraries from the Central Repository. Download Maven from the Apache Maven website.
  3. IronPDF Library: The IronPDF library can be added to a Maven project as a dependency. Include its Maven dependency artifact (along with the optional slf4j dependency) in a Maven project's pom.xml file as shown below:
<dependency>
   <groupId>com.ironsoftware</groupId>
   <artifactId>com.ironsoftware</artifactId>
   <version>2024.9.1</version>
</dependency>

Important steps before writing code

First, add the statement below to the top of the Java source file in which code will be written to import the required IronPDF library classes in the project's scope.

import com.ironsoftware.ironpdf.*;
JAVA

Next, configure IronPDF with a valid license key by invoking the setLicenseKey method in the main method (before any other lines of code).

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

Note: License keys are required to create PDFs without watermarks. Purchase a license key or obtain a free trial license key. Otherwise, continue to the next step (without adding the line above) to generate new PDF documents for free, with watermarks.

Create PDF file from HTML String in Java

Use the renderHtmlAsPdf() method to convert an HTML string to a new PDF document.

In the parameter of renderHtmlAsPdf method, pass a string of HTML markup. IronPDF will convert the HTML content into a new PdfDocument instance.

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

Afterward, use the saveAs method to save the PDF to a path on the local system:

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

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

Create PDF Files from HTML Pages in Java

Use the example below to create a PDF File from an HTML file stored locally in Java:

PdfDocument myPdf = PdfDocument.renderHtmlFileAsPdf("example.html");
// Save the PdfDocument to a file
myPdf.saveAs(Paths.get("html_file_saved.pdf"));
JAVA

As shown above, the renderHtmlFileAsPdf method creates PDF files from HTML files. The method accepts a String (or a Path) containing the path to the HTML file on the filesystem.

IronPDF renders HTML elements in the HTML file, along with any CSS and JavaScript content that influences them, the same way as a web browser would.

Next, invoke the saveAs method with a target file path to save the PDF file to a specific location, just as was done in the previous example.

Create PDF Files from URL in Java

The renderUrlAsPdf method creates PDF Files from web pages referenced by URL. Pass the URL of a webpage as an argument to the method, as below:

PdfDocument urlToPdf = PdfDocument.renderUrlAsPdf("https://ironpdf.com");
// Save the PdfDocument to a file
urlToPdf.saveAs(Paths.get("urlToPdf.pdf"));
JAVA

More information about converting Web Pages to PDFs is available on the URL to PDF Code Example page.

Format PDF Files

Specify desired formatting for the new PDf file using the ChromePdfRenderOptions class. Configurable settings include page orientation, page size, and margin size, just to name a few. Pass an instance of the the ChromePdfRenderOptions class as the second argument to the renderUrlAsPdf method to generate PDF documents with the desired settings. Refer to this Code Example for more information about how to use the ChromePdfRenderOptions class.

Password-Protect PDF Files

IronPDF uses the SecurityOptions class to generate password-protected PDF files. First, create an instance of SecurityOptions, then and use the setUserPassword method to set a password.

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

Security settings are applied to PDFs via their SecurityManager. The next code snippets applies these settings 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. Opening the PDF file will cause a password pop-up to appear:

Java Create PDFs - Figure 1

After entering the correct password, the PDF file will open as expected.

Java Create PDFs - Figure 2

Read more information about additional security and metadata settings here.

Complete Source Code

The complete source file for this tutorial is included below:

//Import statement for IronPDF Java  
import com.ironsoftware.ironpdf.*;
import java.io.IOException;  
import java.nio.file.Paths; 

public class App 
{
    public static void main( String [] args ) throws IOException, PrinterException
    {
     // Apply your license key
        License.setLicenseKey("Your License Key");     
        String htmlString = "<h1>Hello World!</h1><p>This is an example HTML string.</p>";
        PdfDocument pdf = PdfDocument.renderHtmlAsPdf(htmlString);
        pdf.saveAs(Paths.get("html.pdf"));
        PdfDocument myPdf = PdfDocument.renderHtmlFileAsPdf("example.pdf");
        myPdf.saveAs(Paths.get("html_file_saved.pdf"));
        PdfDocument urlToPdf = PdfDocument.renderUrlAsPdf("https://ironpdf.com");
        // Save the PdfDocument to a file
        urlToPdf.saveAs(Paths.get("urlToPdf.pdf"));

        // Password-protect the URLToPdf File.
        SecurityOptions securityOptions = new SecurityOptions();
        securityOptions.setUserPassword("shareable");
        SecurityManager securityManager =  urlToPdf.getSecurity();
        securityManager.setSecurityOptions(securityOptions);       
        urlToPdf.saveAs(Paths.get("protected.pdf"));
    }
}
JAVA

IronPDF renders all images and text without losing any formatting. Buttons are clickable, and text boxes are editable in the PDF file.

Summary

In this How-To Guide, we looked at how Java creates PDFs using IronPDF. IronPDF is a powerful library that allows developers to easily generate and manipulate PDF files in Java.

It also provides a simple and intuitive API that makes it easy to create PDFs from HTML files, XML documents or other sources. Whether you need to generate reports, invoices, or any other type of document, IronPDF can help you get the job done quickly and easily.

IronPDF is not an open-source java library. It has a commercial license which starts from $749. You can get a free trial to test it in production.

Download the software product.