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 thesaveAsmethod 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

How do I create PDF files in Java without losing formatting?

You can use IronPDF to create PDF files in Java without losing formatting by utilizing methods like renderHtmlAsPdf, renderHtmlFileAsPdf, and renderUrlAsPdf. These methods help maintain the original layout and style of the HTML content being converted into PDF.

What functionalities does IronPDF offer for PDF creation in Java?

IronPDF offers functionalities such as adding text, images, and customizing layout in PDFs. It supports converting HTML strings, files, and URLs to PDFs, as well as password-protecting documents using the SecurityOptions class.

How can I convert HTML files to PDF in Java?

To convert HTML files to PDF in Java, use IronPDF's renderHtmlFileAsPdf method. This method reads an HTML file from a given path and converts it into a PDF document, preserving the original formatting.

Can I generate PDFs from a webpage URL using Java?

Yes, with IronPDF, you can generate PDFs from a webpage URL using the renderUrlAsPdf method. Simply provide the URL of the webpage, and IronPDF will convert it into a PDF document.

How do I apply password protection to PDFs in Java?

To apply password protection to PDFs in Java using IronPDF, utilize the SecurityOptions class to set a user password. These options are then applied to the PDF's SecurityManager before saving the document.

What are the steps to integrate IronPDF with a Maven project?

To integrate IronPDF with a Maven project, ensure you have the Java Development Kit (JDK) and Maven installed, then add the IronPDF library as a dependency in your project's pom.xml file.

Is IronPDF for Java open-source?

IronPDF for Java is not open-source; it is a commercial library that requires a license. However, a free trial is available for developers to evaluate the software in their projects.

How can developers automate PDF document creation in Java applications?

Developers can automate PDF document creation in Java applications using IronPDF. It allows for generating documents like invoices and reports on-demand, with full control over formatting and content.

What are the prerequisites for using IronPDF in Java?

The prerequisites for using IronPDF in Java include having the Java Development Kit (JDK), Maven, and the IronPDF library installed in your development environment.

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 ...Read More

Talk to an Expert Five Star Trust Score Rating

Ready to Get Started?