IRONSOFTWAREHOME

HTML to PDF in Java

Curtis Chau
Curtis Chau
Updated: August 2, 2026

IronPDF for Java gives developers a direct path from HTML content to PDF output without learning a separate layout API. The library renders HTML, CSS, and JavaScript the same way a modern browser does, so the PDF output matches what you see on screen. This tutorial covers installation, the three core HTML-to-PDF conversion methods, and formatting options including headers, footers, page sizing, and custom margins.

The tutorial uses IronPDF for Java. A parallel guide covering the .NET version is available at the HTML to PDF conversion tutorial for .NET. IronPDF is also available for Python and Node.js.

Quickstart: Convert HTML to a PDF File

The shortest path to a PDF from an HTML string is three lines of Java code:

import com.ironsoftware.ironpdf.*;
// Convert an HTML string directly to a PDF document
PdfDocument pdf = PdfDocument.renderHtmlAsPdf("<h1>Hello from IronPDF!</h1>");
// Save to disk
pdf.saveAs("output.pdf");
Java

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

First Step:
arrow pointer
Table of Contents

How Do I Add IronPDF to a Maven Project in Java?

Adding IronPDF to a Maven project requires two entries in the project's pom.xml dependency block. The first pulls in the IronPDF library; the second adds an SLF4J logging provider so IronPDF can write engine messages during execution.

<dependency>
  <groupId>com.ironsoftware</groupId>
  <artifactId>ironpdf</artifactId>
  <version>2024.9.1</version>
</dependency>
<dependency>
  <groupId>org.slf4j</groupId>
  <artifactId>slf4j-simple</artifactId>
  <version>2.0.5</version>
</dependency>
XML

The ironpdf artifact references the latest IronPDF for Java release and changelog. The slf4j-simple dependency provides a basic logging backend. You can substitute it with Logback or Log4J as needed, or omit it entirely to suppress log output.

After adding both entries, run mvn install from the project root to download the artifacts. Maven resolves the dependency against Maven Central.

Tips: Check the Maven Central page for com.ironsoftware:ironpdf to confirm the latest version number before adding it to your pom.xml.

How Do I Install the IronPDF JAR Manually in Java?

Projects that do not use Maven or another dependency manager can add IronPDF by downloading the JAR directly and including it on the classpath. Navigate to the IronPDF for Java download page and download the fat-JAR file.

The fat-JAR bundles all dependencies, so no additional classpath entries are required beyond the main artifact. Optionally download an SLF4J implementation JAR to enable logging.

Add both JARs to the project's classpath using your IDE's library management panel, or specify -classpath entries when compiling and running from the terminal.

How Do I Import IronPDF into My Java Source Files?

The com.ironsoftware.ironpdf package contains all conversion and processing components. Place the following import statement at the top of every Java file that calls IronPDF methods.

// Import all IronPDF components
import com.ironsoftware.ironpdf.*;
Java

A targeted import that names specific classes is also valid: import com.ironsoftware.ironpdf.PdfDocument;. The wildcard import is convenient during exploration.

How Do I Set a License Key in IronPDF for Java?

IronPDF for Java is free to use without a license key, but it applies a tiled watermark to all generated or modified PDF documents. To remove the watermark, supply a valid license key before calling any conversion or manipulation method.

// Set the license key before any PDF operations
License.setLicenseKey("YOUR-LICENSE-KEY");
Java

Place the setLicenseKey call at application startup, before any PdfDocument method is called. Purchase a license key or start a free trial to generate PDFs without watermarks.

IronPDF licensing page showing how to obtain a license key to remove watermarks from generated PDFs

A valid license key removes the tiled watermark from generated PDFs. Obtain one at the IronPDF licensing page or request a free trial.

Setting the Log File Location (Optional)

By default, IronPDF writes engine messages to a file named IronPdfEngine.log in the application's root directory. To change the log file path, call Settings.setLogPath before performing any PDF operations.

import java.nio.file.Paths;
// Redirect log output before using IronPDF
Settings.setLogPath(Paths.get("logs/ironpdf-engine.log"));
Java
Please note: The setLogPath call must precede all PdfDocument calls. Calling it after a conversion has started has no effect on that session.

How Do I Convert an HTML String to a PDF in Java?

PdfDocument.renderHtmlAsPdf(String html) converts any valid HTML markup into a PDF document. The method accepts a raw HTML string and returns a PdfDocument object that can be saved, merged, or further modified.

// Convert a minimal HTML string to a PDF document
PdfDocument pdf = PdfDocument.renderHtmlAsPdf("<h1>Hello from IronPDF!</h1>");
// Save the resulting document to disk
pdf.saveAs("html-string-output.pdf");
Java

PDF output from IronPDF renderHtmlAsPdf showing an H1 heading rendered faithfully from an HTML string

IronPDF renders HTML markup directly into a pixel-accurate PDF. The output shown here was generated by the code example above.

The rendering engine is based on Chromium, so any HTML, CSS, or JavaScript that works in Chrome will render correctly in the PDF. This includes Flexbox layouts, CSS Grid, web fonts, SVGs, and JavaScript-driven charts.

An overloaded version of the method accepts a second argument for a base path: renderHtmlAsPdf(String html, String basePath). This base path is used to resolve relative references to local stylesheets, images, and scripts.

// HTML referencing local stylesheet and image
String html = "<html><head><link rel='stylesheet' href='style.css'></head>"
    + "<body><img src='logo.png'/><h1>Invoice</h1></body></html>";
// Provide the folder containing style.css and logo.png as the base path
PdfDocument pdf = PdfDocument.renderHtmlAsPdf(html, "C:/invoices/");
pdf.saveAs("invoice-output.pdf");
Java

The base path can point to a directory on the local filesystem or to a remote URL. IronPDF fetches referenced assets from that location during rendering.

IronPDF renderHtmlAsPdf output showing a full-page document with stylesheet applied, CSS styles preserved from the HTML source

When a base path is provided, IronPDF resolves local CSS and image references to produce a fully styled PDF.

Tips: For local asset resolution to work, all referenced files must be accessible from the base path. Paths using forward slashes work on both Windows and Linux.

For a focused look at this method, see the HTML string to PDF code example.

How Do I Convert a URL to a PDF in Java?

PdfDocument.renderUrlAsPdf(String url) fetches the page at the given URL and renders the full DOM (including JavaScript execution) before saving the output as a PDF.

// Render a live web page to PDF by URL
PdfDocument pdf = PdfDocument.renderUrlAsPdf("https://en.wikipedia.org/wiki/PDF");
// Save the rendered document
pdf.saveAs("wikipedia-pdf-article.pdf");
Java

PDF generated by IronPDF from the Wikipedia PDF article page, showing multi-column layout and navigation elements preserved

IronPDF captures the full rendered state of a web page, including dynamic content produced by JavaScript.

The Chromium rendering engine fetches external stylesheets, fonts, and JavaScript files, so the resulting PDF accurately reflects the page's visual state. This method is well-suited to report generation from web dashboards, archiving public web content, or converting data visualizations that depend on client-side rendering.

Important: URL-to-PDF conversion requires outbound HTTP/HTTPS access from the server running IronPDF. Ensure network policies allow this before deploying to a production environment.

See the dedicated URL to PDF conversion example for additional options such as custom request headers and authentication.

How Do I Convert an HTML File to a PDF in Java?

PdfDocument.renderHtmlFileAsPdf(String filePath) reads an HTML file from the local filesystem and converts it to PDF. The method automatically resolves any relative asset references in the HTML file against the file's directory.

// Convert a local HTML file (with a linked CSS file) to PDF
PdfDocument pdf = PdfDocument.renderHtmlFileAsPdf("C:/invoices/TestInvoice1.html");
// Save the resulting document
pdf.saveAs("invoice-from-file.pdf");
Java

The method handles multi-file HTML projects correctly. In the example above, if TestInvoice1.html links to a stylesheet in the same directory, IronPDF applies that stylesheet during rendering. The result is a PDF that matches the browser-rendered appearance of the source file.

Tips: Use absolute file paths when calling renderHtmlFileAsPdf from a server application. Relative paths are resolved against the JVM's working directory, which may differ from the HTML file's location.

This method is particularly useful for PDF generation workflows that maintain HTML templates on disk: invoice generators, report templates, and form output systems are common use cases.

How Do I Set PDF Page Size and Orientation in Java?

Page size and orientation are controlled through the ChromePdfRenderOptions class. Create a ChromePdfRenderOptions instance, configure the properties, and pass it as the second argument to any renderHtmlAsPdf call.

import com.ironsoftware.ironpdf.*;
import com.ironsoftware.ironpdf.render.*;
// Create rendering options for the PDF
ChromePdfRenderOptions options = new ChromePdfRenderOptions();
// Set paper size to A4
options.setPaperSize(PaperSize.A4);
// Set to landscape orientation
options.setPaperOrientation(PaperOrientation.Landscape);
// Apply options to the conversion
PdfDocument pdf = PdfDocument.renderHtmlAsPdf("<h1>Landscape Report</h1>", options);
pdf.saveAs("landscape-a4-report.pdf");
Java

PaperSize includes standard options such as A4, Letter, Legal, A3, and A5. PaperOrientation accepts Portrait (default) or Landscape.

For non-standard dimensions, use setCustomPaperSizeInMillimeters(double width, double height) or setCustomPaperSizeInInches(double width, double height):

ChromePdfRenderOptions options = new ChromePdfRenderOptions();
// Set a custom 100mm x 150mm page size
options.setCustomPaperSizeInMillimeters(100, 150);
PdfDocument pdf = PdfDocument.renderHtmlAsPdf("<p>Custom size card</p>", options);
pdf.saveAs("custom-size-card.pdf");
Java

See the custom PDF paper size example for the full list of PaperSize constants and sizing options.

How Do I Set Custom Margins on a PDF in Java?

Margin sizes are also set through ChromePdfRenderOptions. The library exposes separate setters for top, bottom, left, and right margins, all accepting values in millimeters.

ChromePdfRenderOptions options = new ChromePdfRenderOptions();
// Set all four margins in millimeters
options.setMarginTop(20);
options.setMarginBottom(20);
options.setMarginLeft(15);
options.setMarginRight(15);
PdfDocument pdf = PdfDocument.renderHtmlAsPdf(
    "<p>Document with custom margins</p>", options);
pdf.saveAs("custom-margins.pdf");
Java

Setting all margins to zero removes white space entirely, which is useful for full-bleed designs such as labels, certificates, or graphic layouts.

Please note: IronPDF margin values are in millimeters. A value of 0 disables the margin on that edge. Note that printer driver margins are separate from IronPDF margins, so content that fills the page edge-to-edge may still be clipped when printed.

For a working code sample, visit the custom margins example.

How Do I Add Headers and Footers to a PDF in Java?

IronPDF supports two types of headers and footers: text-based (TextHeaderFooter) and HTML-based (HtmlHeaderFooter). Text headers are quick to configure; HTML headers support full styling and images.

import com.ironsoftware.ironpdf.*;
import com.ironsoftware.ironpdf.headerfooter.*;
import com.ironsoftware.ironpdf.render.*;
ChromePdfRenderOptions options = new ChromePdfRenderOptions();
// Configure a text-based header
TextHeaderFooter header = new TextHeaderFooter();
// Use merge fields: {page}, {total-pages}, {date}, {time}, {url}, {html-title}
header.setCenterText("Report Title");
header.setRightText("Page {page} of {total-pages}");
options.setTextHeader(header);
// Configure a text-based footer
TextHeaderFooter footer = new TextHeaderFooter();
footer.setLeftText("Confidential");
footer.setCenterText("{date}");
options.setTextFooter(footer);
PdfDocument pdf = PdfDocument.renderHtmlAsPdf(
    "<h1>Annual Report</h1><p>Content here.</p>", options);
pdf.saveAs("report-with-headers.pdf");
Java

The {page}, {total-pages}, {date}, {time}, {url}, and {html-title} merge fields are replaced at render time with document-specific values.

Adding an HTML Header

For headers that require logos, brand colors, or complex layouts, use HtmlHeaderFooter:

import com.ironsoftware.ironpdf.headerfooter.*;
HtmlHeaderFooter header = new HtmlHeaderFooter();
header.setHtmlFragment(
    "<div style='background:#003366;color:white;padding:8px;font-family:Arial;'>"
    + "<img src='/images/logo.png' style='height:30px;float:left;'/>"
    + "<span style='line-height:30px;margin-left:10px;'>Company Report</span>"
    + "</div>"
);
ChromePdfRenderOptions options = new ChromePdfRenderOptions();
options.setHtmlHeader(header);
PdfDocument pdf = PdfDocument.renderHtmlAsPdf(
    "<h1>Q3 Results</h1>", options);
pdf.saveAs("report-with-html-header.pdf");
Java
Tips: HTML header fragments are rendered in their own page context. External image paths must be absolute URLs or paths accessible from the server running IronPDF.

See the headers and footers code example for additional merge field options and multi-page behavior.

How Do I Apply a Watermark to a PDF in Java?

IronPDF applies watermarks by stamping HTML content onto existing PDF pages. This approach gives full control over positioning, transparency, and styling.

import com.ironsoftware.ironpdf.*;
// Create the base PDF
PdfDocument pdf = PdfDocument.renderHtmlAsPdf("<h1>Confidential Report</h1>");
// Apply a diagonal text watermark using HTML stamping
String watermarkHtml =
    "<div style='position:absolute;top:50%;left:50%;transform:translate(-50%,-50%) rotate(-45deg);"
    + "font-size:80px;color:rgba(200,0,0,0.15);font-family:Arial;font-weight:bold;"
    + "white-space:nowrap;pointer-events:none;'>CONFIDENTIAL</div>";
pdf.applyStamp(watermarkHtml);
pdf.saveAs("watermarked-report.pdf");
Java

The applyStamp method accepts standard HTML/CSS. Using a semi-transparent rgba color for the text ensures the watermark is visible without obscuring the document content beneath it.

For image-based watermarks or watermarks applied to specific page ranges, see the custom watermark how-to guide for Java.

How Do I Compress a PDF File in Java?

For PDF files that contain images, IronPDF can reduce file size by resampling embedded images to a lower resolution. Use compressImages on an existing PdfDocument.

// Load an existing PDF or use one created by IronPDF
PdfDocument pdf = PdfDocument.fromFile(Paths.get("large-report.pdf"));
// Reduce image quality to 60% (value range: 1–100)
pdf.compressImages(60);
// Save the compressed document
pdf.saveAs("compressed-report.pdf");
Java

The quality parameter is an integer from 1 to 100, where 100 preserves full image quality and lower values reduce file size at the cost of image fidelity. A value of 60 to 80 gives a practical balance between size and visual quality for most business documents.

Warning: Image compression is destructive. The original image data cannot be recovered from a compressed PDF. Always keep the source file if the original quality may be needed later.

See the PDF compression example for more details on image quality thresholds.

Next Steps

This tutorial covered the three HTML-to-PDF conversion methods (string, URL, and file) along with page sizing, margins, headers, footers, watermarks, and compression. These are the most common PDF formatting operations for Java server applications.

To go further with IronPDF for Java:

Start a free trial to generate PDFs without watermarks, or view licensing options to add IronPDF to a production project.


Tutorial Quick Access

IronPDF for Java IntelliJ project download

Download this Tutorial as Java Source Code

The full HTML to PDF Java source code for this tutorial is available to download for free as a zipped IntelliJ project.

Download

Explore this Tutorial on GitHub

The source code for this project is available on GitHub as an IntelliJ IDEA project that can also be imported into Eclipse or other Java IDEs.

IronPDF for Java format-pdfs examples
GitHub repository for IronPDF Java tutorial source code
IronPDF Java API reference documentation

View the API Reference

Explore the API reference for IronPDF for Java, covering the details of all classes, methods, fields, and enums in the com.ironsoftware.ironpdf package.

View the IronPDF Java API Reference

Frequently Asked Questions

How can I convert HTML to PDF in Java using IronPDF?

You can convert HTML to PDF in Java using IronPDF by installing the library and utilizing the method `PdfDocument.renderHtmlAsPdf(String html)` which converts HTML strings directly into PDF documents.

Can IronPDF for Java handle CSS and JavaScript during PDF conversion?

Yes, IronPDF for Java renders HTML, CSS, and JavaScript just like a modern browser, ensuring that the PDF output accurately reflects the on-screen representation.

How do I set a license key in IronPDF for Java?

To set a license key in IronPDF for Java, use `License.setLicenseKey("YOUR-LICENSE-KEY")` before performing any PDF operations to remove watermarks from generated PDFs.

Is it possible to add headers and footers to a PDF using IronPDF for Java?

Yes, you can add text or HTML headers and footers to PDFs using IronPDF for Java with `TextHeaderFooter` and `HtmlHeaderFooter` classes for custom styling and content.

How do I handle page size and orientation in PDFs generated by IronPDF for Java?

You can control PDF page size and orientation by configuring `ChromePdfRenderOptions` and passing it to the conversion method. Options include standard sizes like A4, and orientations like portrait or landscape.

Can IronPDF for Java convert a web page URL directly to a PDF?

Yes, use `PdfDocument.renderUrlAsPdf(String url)` to fetch and render a webpage as a PDF document, including executing JavaScript and fetching stylesheets.

What are the margin customization options in IronPDF for Java?

IronPDF for Java allows you to set custom margins for PDFs using the `ChromePdfRenderOptions` class, with different values for top, bottom, left, and right margins specified in millimeters.

How can I apply a watermark to a PDF using IronPDF for Java?

Apply a watermark to a PDF by using the `applyStamp` method in IronPDF, which allows you to overlay HTML content, such as text or images, on the existing PDF pages.

Does IronPDF for Java support compressing PDF files?

Yes, IronPDF for Java supports file compression by reducing the quality of images in a PDF, which can significantly lower the file size using the `compressImages` method.

How can I convert an HTML file to a PDF with IronPDF for Java?

Convert an HTML file to a PDF by using `PdfDocument.renderHtmlFileAsPdf(String filePath)`, which reads the file and converts it while resolving any relative asset references based on the file’s directory.

Curtis Chau
Technical Writer

Curtis Chau holds a Bachelor’s degree in Computer Science (Carleton University) and specializes in front-end development with expertise in Node.js, TypeScript, JavaScript, and React. Passionate about crafting intuitive and aesthetically pleasing user interfaces, Curtis enjoys working with modern frameworks and creating well-structured, visually appealing manuals.

...
Read More

Ready to Get Started?

Version:2026.8just released

Get your free 30-day Trial Key instantly.
No credit card or account creation required
Java Maven Library for PDF
Install with Maven

Version: 2026.8

<dependency>
   <groupId>com.ironsoftware</groupId>
   <artifactId>ironpdf</artifactId>
   <version>2026.8.2</version>
</dependency>
https://central.sonatype.com/artifact/com.ironsoftware/ironpdf/2026.8.2
or
Java PDF JAR
Download JAR

Version: 2026.8

Manually install into your project

Key in blue circle

Get your free 30-day Trial Key instantly.

Your trial license will be sent to your email address

No limitations. 100% unlocked. No credit card.

OR
bullet_checkedNo credit card or account creation requiredNo limitations. 100% unlocked. No credit card.
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried Iron Suite
Book your free Live Demo
Booking Badge

Trusted by Millions of Engineers Worldwide

Iron Software's customer logos
Get Your No-Obligation Consult
Complete the form below or email sales@ironsoftware.com
Your details will always be kept confidential.
Trusted by Millions of Engineers Worldwide
Iron Software's customer logos
Get your free 30-day Trial Key instantly.
No credit card or account creation required
Java Maven Library for PDF
Install with Maven

Version: 2026.8

<dependency>
   <groupId>com.ironsoftware</groupId>
   <artifactId>ironpdf</artifactId>
   <version>2026.8.2</version>
</dependency>
https://central.sonatype.com/artifact/com.ironsoftware/ironpdf/2026.8.2
or
Java PDF JAR
Download JAR

Version: 2026.8

Manually install into your project