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>ironpdf</artifactId>
    <version>1.0.0</version>
</dependency>
<dependency>
    <groupId>com.ironsoftware</groupId>
    <artifactId>ironpdf</artifactId>
    <version>1.0.0</version>
</dependency>
XML

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.*;
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");
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.

// HTML content to be converted to PDF
String htmlString = "<h1>Hello World!</h1><p>This is an example HTML string.</p>";

// Convert HTML string to PDF
PdfDocument pdf = PdfDocument.renderHtmlAsPdf(htmlString);

// Save the PDF document to a file
pdf.saveAs(Paths.get("html.pdf"));
// HTML content to be converted to PDF
String htmlString = "<h1>Hello World!</h1><p>This is an example HTML string.</p>";

// Convert HTML string to PDF
PdfDocument pdf = PdfDocument.renderHtmlAsPdf(htmlString);

// Save the PDF document to a file
pdf.saveAs(Paths.get("html.pdf"));
JAVA

The 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:

// Convert HTML file to PDF
PdfDocument myPdf = PdfDocument.renderHtmlFileAsPdf("example.html");

// Save the PdfDocument to a file
myPdf.saveAs(Paths.get("html_file_saved.pdf"));
// Convert HTML file to PDF
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:

// Convert a URL to PDF
PdfDocument urlToPdf = PdfDocument.renderUrlAsPdf("https://ironpdf.com");

// Save the PdfDocument to a file
urlToPdf.saveAs(Paths.get("urlToPdf.pdf"));
// Convert a URL to PDF
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 ChromePdfRenderOptions class as the second argument to the renderUrlAsPdf method to generate PDF documents with the desired settings. Refer to this PDF Generation Settings 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 use the setUserPassword method to set a password.

// Create security options and set user password
SecurityOptions securityOptions = new SecurityOptions();
securityOptions.setUserPassword("shareable");
// Create security options and set user password
SecurityOptions securityOptions = new SecurityOptions();
securityOptions.setUserPassword("shareable");
JAVA

Security settings are applied to PDFs via their SecurityManager. The next code snippets apply these settings to the PDF document that we created in the URL to PDF example:

// Apply security options to the PDF
SecurityManager securityManager = urlToPdf.getSecurity();
securityManager.setSecurityOptions(securityOptions);

// Save the password-protected PDF document
urlToPdf.saveAs("protected.pdf");
// Apply security options to the PDF
SecurityManager securityManager = urlToPdf.getSecurity();
securityManager.setSecurityOptions(securityOptions);

// Save the password-protected PDF document
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 on the Security and Metadata Example Page.

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 {
        // Apply your license key
        License.setLicenseKey("Your License Key");

        // Convert HTML string to a PDF and save it
        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"));

        // Convert HTML file to a PDF and save it
        PdfDocument myPdf = PdfDocument.renderHtmlFileAsPdf("example.html");
        myPdf.saveAs(Paths.get("html_file_saved.pdf"));

        // Convert URL to a PDF and save it
        PdfDocument urlToPdf = PdfDocument.renderUrlAsPdf("https://ironpdf.com");
        urlToPdf.saveAs(Paths.get("urlToPdf.pdf"));

        // Password-protect the PDF file
        SecurityOptions securityOptions = new SecurityOptions();
        securityOptions.setUserPassword("shareable");
        SecurityManager securityManager = urlToPdf.getSecurity();
        securityManager.setSecurityOptions(securityOptions);
        urlToPdf.saveAs(Paths.get("protected.pdf"));
    }
}
// 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 {
        // Apply your license key
        License.setLicenseKey("Your License Key");

        // Convert HTML string to a PDF and save it
        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"));

        // Convert HTML file to a PDF and save it
        PdfDocument myPdf = PdfDocument.renderHtmlFileAsPdf("example.html");
        myPdf.saveAs(Paths.get("html_file_saved.pdf"));

        // Convert URL to a PDF and save it
        PdfDocument urlToPdf = PdfDocument.renderUrlAsPdf("https://ironpdf.com");
        urlToPdf.saveAs(Paths.get("urlToPdf.pdf"));

        // Password-protect the PDF 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 IronPDF Java Library.

Frequently Asked Questions

What is a Java library for creating PDF documents from HTML?

IronPDF is a Java library designed to create PDF documents from HTML. It provides functions for adding text, images, and customizing PDFs, and is built on top of the .NET Framework, allowing use in both .NET and Java applications.

How can I create a PDF from an HTML string?

You can create a PDF from an HTML string using the 'renderHtmlAsPdf' method provided by IronPDF. Pass a string of HTML markup to this method, which will convert it into a new PdfDocument instance that can be saved as a PDF file.

What are the prerequisites for using a Java library to create PDFs in a Maven project?

The prerequisites include installing the Java Development Kit (JDK), Maven, and adding the IronPDF library to your Maven project as a dependency.

Can a Java library create a PDF from a URL?

Yes, IronPDF can create a PDF from a URL using the 'renderUrlAsPdf' method. By passing the URL of a webpage, IronPDF will convert it into a PDF document.

How do I password-protect a PDF?

To password-protect a PDF, use the 'SecurityOptions' class provided by IronPDF to set a user password. Apply these options to the PDF's SecurityManager, then save the PDF document.

Is this Java library an open-source library?

No, IronPDF is not an open-source library. It requires a commercial license, although a free trial is available for testing in production.

How can I format PDF files?

You can format PDF files using the 'ChromePdfRenderOptions' class in IronPDF to specify settings like page orientation, size, and margins. Pass an instance of this class as an argument to the 'renderUrlAsPdf' method.

What methods are available for creating PDFs from HTML?

IronPDF provides methods like 'renderHtmlAsPdf' for HTML strings, 'renderHtmlFileAsPdf' for HTML files, and 'renderUrlAsPdf' for URLs to create PDFs from HTML content.

Why would developers use a Java library in their applications?

Developers use IronPDF to automate PDF document creation within applications, useful for generating documents like invoices or reports on-demand, while maintaining control over formatting and content.

Darrius Serrant
Full Stack Software Engineer (WebOps)

Darrius Serrant holds a Bachelor’s degree in Computer Science from the University of Miami and works as a Full Stack WebOps Marketing Engineer at Iron Software. Drawn to coding from a young age, he saw computing as both mysterious and accessible, making it the perfect medium for creativity and problem-solving.

At Iron Software, Darrius enjoys creating new things and simplifying complex concepts to make them more understandable. As one of our resident developers, he has also volunteered to teach students, sharing his expertise with the next generation.

For Darrius, his work is fulfilling because it is valued and has a real impact.

Talk to an Expert Five Star Trust Score Rating

Ready to Get Started?