HTML to PDF in Java

This tutorial instructs Java developers on how to use the IronPDF library to convert HTML content into pixel-perfect PDF (portable document format) documents.

IronPDF is a fully-featured PDF converter and PDF processing library. IronPDF is available for both .NET and Java programming languages. This tutorial covers the library's use for converting HTML content (files, markup, etc) in Java applications. The tutorial for converting HTML to PDF in .NET applications is available in the HTML to PDF .NET tutorial.


How to Convert HTML to PDF in Java

How to Convert HTML to PDF in Java

  1. Install Java library to convert HTML to PDF
  2. Convert HTML String to PDF document using renderHtmlAsPdf method
  3. Generate PDF files from website URL in Java
  4. Convert HTML files to PDF files with renderHtmlFileAsPdf method
  5. Save the generated PDF as a new file

Getting Started

Start using IronPDF in your project today with a free trial.

First Step:
green arrow pointer


1. Installing the IronPDF PDF Library for Java

There are two ways to incorporate the IronPDF Library in a Java Project:

  1. Add IronPDF as a dependency in a Maven-configured Java Project
  2. Download the IronPDF JAR File and add it to the project classpath manually.

The following section will briefly cover both installation methods.

Option 1: Install IronPDF as a Maven Dependency

To install IronPDF in a Java project using Maven, add the following artifacts to the dependency section of the Java project's pom.xml file.

<dependencies>
    <!-- IronPDF Library -->
    <dependency>
        <groupId>com.ironsoftware</groupId>
        <artifactId>ironpdf</artifactId>
        <version>[LATEST_VERSION]</version>
    </dependency>

    <!-- SLF4J for logging (optional but recommended) -->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-simple</artifactId>
        <version>[LATEST_VERSION]</version>
    </dependency>
</dependencies>
<dependencies>
    <!-- IronPDF Library -->
    <dependency>
        <groupId>com.ironsoftware</groupId>
        <artifactId>ironpdf</artifactId>
        <version>[LATEST_VERSION]</version>
    </dependency>

    <!-- SLF4J for logging (optional but recommended) -->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-simple</artifactId>
        <version>[LATEST_VERSION]</version>
    </dependency>
</dependencies>
XML

The first artifact references the latest version of the IronPDF library. The second artifact references an SLF4J implementation. This dependency is required to enable IronPDF's rendering engine to generate logging messages during execution. Software engineers can substitute this dependency for other logging providers (such as Logback and Log4J); or omit it entirely if they do not need or desire logging.

Run the mvn install command inside a terminal at the Java project's root directory to download the previously mentioned libraries.

Option 2: Install the IronPDF JAR Manually

Developers who prefer not to use Maven or any other dependency management system will need to download the IronPDF library JAR file (and the optional SLF4J implementation) and manually add it to their project's class path.

Download the IronPDF JAR file directly from IronPDF JAR download (or from the Maven Repository).


2. Converting HTML to PDF

This section showcases IronPDF's flagship HTML-to-PDF rendering abilities.

The PdfDocument class is the entry point for all of IronPDF's PDF document rendering and manipulation features. The class includes a set of robust methods for converting HTML to PDF documents in support of the following three use cases: converting from HTML string/markup, converting from an HTML file, and converting from a URL. This section will briefly cover each of these use cases, with links to additional content for gathering additional information.

2.1 Import the IronPDF Package

All of IronPDF's conversion and processing components are contained in the com.ironsoftware.ironpdf package.

Include the following import statement at the top of the Java source files (where IronPDF will be used) to make these components accessible to the application's source code.

// Import statement for IronPDF for Java
import com.ironsoftware.ironpdf.*;
// Import statement for IronPDF for Java
import com.ironsoftware.ironpdf.*;
JAVA

2.2. Set the License Key (optional)

IronPDF for Java is free to use. However, for free users, it will brand PDF documents with a tiled background watermark (as shown in the image below).

Image showing watermark

To use IronPDF to generate PDFs without the watermarks, the library must use a valid license key. The line of code below configures the library with a license key.

// Apply your license key
License.setLicenseKey("YOUR-LICENSE-KEY");
// Apply your license key
License.setLicenseKey("YOUR-LICENSE-KEY");
JAVA

The license key should be set before generating PDF files or customizing file content. We recommend that you call the setLicenseKey method before all other lines of code.

Purchase a license key from the IronPDF licensing page, or contact us to obtain a free trial license key.

2.3 Set the Log File Location (optional)

By default (and assuming that there is an SLF4J provider installed), IronPDF generates log messages to a text file called IronPdfEngine.log located in the Java application's root directory.

To specify a different name and location for the log file, use the Settings.setLogPath method:

// Set a log path
Settings.setLogPath(Paths.get("IronPdfEngine.log"));
// Set a log path
Settings.setLogPath(Paths.get("IronPdfEngine.log"));
JAVA

Please note
Settings.setLogPath must be called before using any PDF conversion and manipulation methods.

2.4. Creating a PDF from HTML String

PdfDocument.renderHtmlAsPdf converts a string of HTML content into a PDF document.

The following code sample uses a single headline element to generate a new file.

// Convert HTML string to PDF document
PdfDocument pdf = PdfDocument.renderHtmlAsPdf("<h1>Hello from IronPDF!</h1>");
// Save the PDF document
pdf.saveAs("htmlstring_to_pdf.pdf");
// Convert HTML string to PDF document
PdfDocument pdf = PdfDocument.renderHtmlAsPdf("<h1>Hello from IronPDF!</h1>");
// Save the PDF document
pdf.saveAs("htmlstring_to_pdf.pdf");
JAVA

Conversion from HTML string to PDF

renderHtmlAsPdf processes all HTML, CSS, and JavaScript content the same way that modern, standards-compliant browsers can. This helps software engineers create PDF documents that look exactly as it appears in a web browser.

The renderHtmlAsPdf method can source images, stylesheets, and scripts located in folders on a computer or on a network drive. The next example produces a PDF document from HTML that references a CSS file and an image located in an assets folder:

// HTML string with external assets
String html = "<html><head><title>Hello world!</title><link rel='stylesheet' href='assets/style.css'></head><body><h1>Hello from IronPDF!</h1><a href='https://ironpdf.com/java/'><img src='assets/logo.png' /></a></body></html>";
// Convert HTML to PDF
PdfDocument pdf = PdfDocument.renderHtmlAsPdf(html);
// Save the PDF document
pdf.saveAs("output.pdf");
// HTML string with external assets
String html = "<html><head><title>Hello world!</title><link rel='stylesheet' href='assets/style.css'></head><body><h1>Hello from IronPDF!</h1><a href='https://ironpdf.com/java/'><img src='assets/logo.png' /></a></body></html>";
// Convert HTML to PDF
PdfDocument pdf = PdfDocument.renderHtmlAsPdf(html);
// Save the PDF document
pdf.saveAs("output.pdf");
JAVA

Conversion result with external assets

A second (optional) argument to renderHtmlAsPdf allows developers to specify a base path from which to reference web assets. This path can be to a directory on the local filesystem or even a URL path.

Learn more about the renderHtmlAsPdf method from this code example on using HTML to create a PDF, or read about it in the API Reference page for PdfDocument class.

2.5. Creating a PDF from a URL

Developers can convert online web pages to PDF documents using IronPDF's PdfDocument.renderUrlAsPdf method.

The next example renders the Wikipedia article into PDF content.

// Convert a URL to PDF
PdfDocument pdf = PdfDocument.renderUrlAsPdf("https://en.wikipedia.org/wiki/PDF");
// Save the PDF document
pdf.saveAs("url_to_pdf.pdf");
// Convert a URL to PDF
PdfDocument pdf = PdfDocument.renderUrlAsPdf("https://en.wikipedia.org/wiki/PDF");
// Save the PDF document
pdf.saveAs("url_to_pdf.pdf");
JAVA

URL to PDF conversion result

Learn more about converting web pages into PDF content from this code example on converting a URL to a PDF.

2.6. Creating a PDF from an HTML File

IronPDF can also render an HTML document stored on a local filesystem directly into its equivalent PDF format.

The next code example uses this invoice as a real-world demonstration of how well IronPDF can convert HTML files.

The HTML markup for the invoice is reproduced here for convenience:

<html>
<head>
    <meta charset="utf-8">
    <title>Invoice</title>
    <link rel="stylesheet" href="style.css">
    <link rel="license" href="https://www.opensource.org/licenses/mit-license/">
    <script src="script.js"></script>
</head>
<body>
<header>
    <h1>Invoice</h1>
    <address contenteditable>
        <p>Jonathan Neal</p>
        <p>101 E. Chapman Ave<br>Orange, CA 92866</p>
        <p>(800) 555-1234</p>
    </address>
    <span><img alt="" src="http://www.jonathantneal.com/examples/invoice/logo.png"><input type="file" accept="image/*"></span>
</header>
<article>
    <h1>Recipient</h1>
    <address contenteditable>
        <p>Some Company<br>c/o Some Guy</p>
    </address>
    <table class="meta">
        <tr>
            <th><span contenteditable>Invoice #</span></th>
            <td><span contenteditable>101138</span></td>
        </tr>
        <tr>
            <th><span contenteditable>Date</span></th>
            <td><span contenteditable>January 1, 2012</span></td>
        </tr>
        <tr>
            <th><span contenteditable>Amount Due</span></th>
            <td><span id="prefix" contenteditable>$</span><span>600.00</span></td>
        </tr>
    </table>
    <table class="inventory">
        <thead>
        <tr>
            <th><span contenteditable>Item</span></th>
            <th><span contenteditable>Description</span></th>
            <th><span contenteditable>Rate</span></th>
            <th><span contenteditable>Quantity</span></th>
            <th><span contenteditable>Price</span></th>
        </tr>
        </thead>
        <tbody>
        <tr>
            <td><a class="cut">-</a><span contenteditable>Front End Consultation</span></td>
            <td><span contenteditable>Experience Review</span></td>
            <td><span data-prefix>$</span><span contenteditable>150.00</span></td>
            <td><span contenteditable>4</span></td>
            <td><span data-prefix>$</span><span>600.00</span></td>
        </tr>
        </tbody>
    </table>
    <a class="add">+</a>
    <table class="balance">
        <tr>
            <th><span contenteditable>Total</span></th>
            <td><span data-prefix>$</span><span>600.00</span></td>
        </tr>
        <tr>
            <th><span contenteditable>Amount Paid</span></th>
            <td><span data-prefix>$</span><span contenteditable>0.00</span></td>
        </tr>
        <tr>
            <th><span contenteditable>Balance Due</span></th>
            <td><span data-prefix>$</span><span>600.00</span></td>
        </tr>
    </table>
</article>
<aside>
    <h1><span contenteditable>Additional Notes</span></h1>
    <div contenteditable>
        <p>A finance charge of 1.5% will be made on unpaid balances after 30 days.</p>
    </div>
</aside>
</body>
</html>
<html>
<head>
    <meta charset="utf-8">
    <title>Invoice</title>
    <link rel="stylesheet" href="style.css">
    <link rel="license" href="https://www.opensource.org/licenses/mit-license/">
    <script src="script.js"></script>
</head>
<body>
<header>
    <h1>Invoice</h1>
    <address contenteditable>
        <p>Jonathan Neal</p>
        <p>101 E. Chapman Ave<br>Orange, CA 92866</p>
        <p>(800) 555-1234</p>
    </address>
    <span><img alt="" src="http://www.jonathantneal.com/examples/invoice/logo.png"><input type="file" accept="image/*"></span>
</header>
<article>
    <h1>Recipient</h1>
    <address contenteditable>
        <p>Some Company<br>c/o Some Guy</p>
    </address>
    <table class="meta">
        <tr>
            <th><span contenteditable>Invoice #</span></th>
            <td><span contenteditable>101138</span></td>
        </tr>
        <tr>
            <th><span contenteditable>Date</span></th>
            <td><span contenteditable>January 1, 2012</span></td>
        </tr>
        <tr>
            <th><span contenteditable>Amount Due</span></th>
            <td><span id="prefix" contenteditable>$</span><span>600.00</span></td>
        </tr>
    </table>
    <table class="inventory">
        <thead>
        <tr>
            <th><span contenteditable>Item</span></th>
            <th><span contenteditable>Description</span></th>
            <th><span contenteditable>Rate</span></th>
            <th><span contenteditable>Quantity</span></th>
            <th><span contenteditable>Price</span></th>
        </tr>
        </thead>
        <tbody>
        <tr>
            <td><a class="cut">-</a><span contenteditable>Front End Consultation</span></td>
            <td><span contenteditable>Experience Review</span></td>
            <td><span data-prefix>$</span><span contenteditable>150.00</span></td>
            <td><span contenteditable>4</span></td>
            <td><span data-prefix>$</span><span>600.00</span></td>
        </tr>
        </tbody>
    </table>
    <a class="add">+</a>
    <table class="balance">
        <tr>
            <th><span contenteditable>Total</span></th>
            <td><span data-prefix>$</span><span>600.00</span></td>
        </tr>
        <tr>
            <th><span contenteditable>Amount Paid</span></th>
            <td><span data-prefix>$</span><span contenteditable>0.00</span></td>
        </tr>
        <tr>
            <th><span contenteditable>Balance Due</span></th>
            <td><span data-prefix>$</span><span>600.00</span></td>
        </tr>
    </table>
</article>
<aside>
    <h1><span contenteditable>Additional Notes</span></h1>
    <div contenteditable>
        <p>A finance charge of 1.5% will be made on unpaid balances after 30 days.</p>
    </div>
</aside>
</body>
</html>
HTML

Assume that the HTML file has been saved to a folder called "invoices" along with its CSS file and JavaScript file. We can use IronPDF to convert the HTML file as follows:

// Convert an HTML file to PDF
PdfDocument pdf = PdfDocument.renderHtmlFileAsPdf("C:/invoices/TestInvoice1.html");
// Save the PDF document
pdf.saveAs("htmlfile_to_pdf.pdf");
// Convert an HTML file to PDF
PdfDocument pdf = PdfDocument.renderHtmlFileAsPdf("C:/invoices/TestInvoice1.html");
// Save the PDF document
pdf.saveAs("htmlfile_to_pdf.pdf");
JAVA

As with the HTML string to PDF conversion examples, IronPDF correctly resolves any relative URLs in an HTML document to their correct paths on the file system. As a result, the PDF File that this example produces is able to perfectly capture the visual influences that any referenced stylesheets and scripts would normally have on a web page.

3. Further Reading

We have only scratched the surface of IronPDF's HTML to PDF rendering abilities.

Further your understanding of how to use the HTML to PDF converter for Java development using the curated code samples featured in our Code Examples section.

  1. Read this code example for PDF generation settings to learn how to customize the appearance of a PDF document during the conversion process.
  2. Generate PDF files with custom headers and footers, margin sizes, page dimensions, watermarks, and much more.
  3. Extract PDF content (text extraction from PDFs and image extraction from PDFs) from documents, optimize file sizes with PDF compression, and print PDFs programmatically with IronPrint capabilities.

Study the IronPDF Java API Reference page on the PdfDocument class for even greater control over rendered HTML to PDF.

Frequently Asked Questions

What is a library for converting HTML to PDF?

IronPDF is a fully-featured PDF converter and PDF processing library available for .NET and Java programming languages.

How do I install a library to convert HTML to PDF in a Java project using Maven?

To install IronPDF using Maven, add the IronPDF dependency to the dependency section of the Java project's pom.xml file and run 'mvn install' in the project's root directory.

Can I use a PDF library without Maven?

Yes, you can download the IronPDF JAR file and manually add it to the project's classpath if you prefer not to use Maven or any other dependency management system.

How do I convert an HTML string to a PDF?

Use the 'PdfDocument.renderHtmlAsPdf' method in IronPDF to convert an HTML string into a PDF document and then save the document using the 'saveAs' method.

Can a library convert web pages to PDF?

Yes, IronPDF can convert online web pages to PDF documents using the 'PdfDocument.renderUrlAsPdf' method.

Is it possible to convert an HTML file to a PDF?

Yes, IronPDF can render an HTML document stored on a local filesystem directly into its equivalent PDF format using the 'PdfDocument.renderHtmlFileAsPdf' method.

How do I remove watermarks from PDFs generated by a PDF library?

To remove watermarks, you need to use a valid license key with IronPDF. Set the license key using the 'License.setLicenseKey' method before generating PDF files.

Does a PDF library support logging?

Yes, IronPDF supports logging using SLF4J. You can set a log file location using the 'Settings.setLogPath' method if an SLF4J provider is installed.

Where can I find more examples of using a PDF library?

You can find more examples and further reading on IronPDF's rendering abilities in the Code Examples section and the IronPDF Java API Reference page.

How can I customize PDF generation settings in a PDF library?

You can customize the appearance of PDF documents during the conversion process by exploring examples for PDF generation settings, such as headers, footers, margin sizes, and more in the Code Examples section.

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.