HTML to PDF in Java: 5 Libraries Compared (openhtmltopdf, iText, Flying Saucer, OpenPDF, Playwright)
Generating PDFs from custom HTML content or directly from website URLs is a common requirement for many real-world applications. In the past, this required writing a lot of custom code and took a lot of time, but now there are many libraries and tools that can do this with just a few lines of code.

This guide compares five Java libraries that convert HTML to PDF. Every code example below was compiled and run against the library’s current release in November 2026. An HTML to PDF API is another option, covered at the end.
Which Java library should you use?
The five fall into two groups. Four are layout engines written in Java: they read XHTML and CSS and draw the PDF themselves, with no browser, so they are fast and light, but they don’t run JavaScript. Playwright drives a real Chromium browser instead, so the PDF matches what Chrome shows, at the cost of running a browser.
- openhtmltopdf: the usual choice for documents you control, such as invoices and reports. Built on Apache PDFBox, with good support for print CSS: page sizes, page numbers and repeating table headers.
- iText pdfHTML: the most complete CSS support of the four Java engines, including flexbox and grid, and it accepts HTML that isn’t well-formed. It is AGPL, so closed-source use needs a commercial licence.
- Flying Saucer: the original Java XHTML renderer, now drawing its PDFs with OpenPDF. Similar results to openhtmltopdf.
- OpenPDF: OpenPDF 3 adds an HTML module,
openpdf-html, which also parses ordinary HTML that isn’t XHTML. - Playwright for Java: for live web pages, and anything that needs JavaScript or modern CSS.
To convert HTML to PDF with Apache PDFBox, use openhtmltopdf. PDFBox writes PDF files but cannot lay out HTML; openhtmltopdf lays out the HTML and draws it with PDFBox.
Prerequisites
The examples use Maven for dependencies. They use text blocks, so they need Java 15 or newer, and Flying Saucer 10 and OpenPDF 3 themselves need Java 21. The other libraries still run on Java 8. If you do not have Maven, the official website explains how to get started.
Converting HTML to PDF using Java Libraries
openhtmltopdf (with Apache PDFBox)
openhtmltopdf renders XHTML and CSS 2.1 and draws the result with Apache PDFBox. It supports the print CSS that documents need: @page sizes and margins, page numbers with counter(page), and table headers that repeat on every page. It is licensed LGPL 2.1 or later.
The project has moved. The old com.openhtmltopdf artifacts stopped at version 1.0.10 in 2021, so use the maintained fork:
<dependency>
<groupId>io.github.openhtmltopdf</groupId>
<artifactId>openhtmltopdf-pdfbox</artifactId>
<version>1.1.114</version>
</dependency>Generate PDF from custom HTML content
import com.openhtmltopdf.pdfboxout.PdfRendererBuilder;
import java.io.FileOutputStream;
import java.io.OutputStream;
public class OpenHtmlToPdfExample {
public static void main(String[] args) throws Exception {
String html = """
<html>
<head>
<style>
@page { size: A4; margin: 20mm; }
body { font-family: sans-serif; }
h1 { color: #2563eb; }
</style>
</head>
<body>
<h1>Invoice INV-1001</h1>
<p>Total: $250.00</p>
</body>
</html>
""";
try (OutputStream os = new FileOutputStream("invoice.pdf")) {
PdfRendererBuilder builder = new PdfRendererBuilder();
builder.withHtmlContent(html, null);
builder.toStream(os);
builder.run();
}
}
}withHtmlContent takes the HTML and a base URI, which resolves relative paths to images and stylesheets (null here, because there are none). The HTML has to be well-formed XHTML: every tag closed and every attribute value quoted.
Generate PDF from a website URL, or from HTML that isn’t XHTML
Real web pages are rarely well-formed XHTML, so parse them with jsoup first and give openhtmltopdf the cleaned-up document. Add jsoup to your project:
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.24.1</version>
</dependency>import com.openhtmltopdf.pdfboxout.PdfRendererBuilder;
import org.jsoup.Jsoup;
import org.jsoup.helper.W3CDom;
import java.io.FileOutputStream;
import java.io.OutputStream;
public class OpenHtmlToPdfFromUrl {
public static void main(String[] args) throws Exception {
// jsoup turns real-world HTML into a well-formed document
org.jsoup.nodes.Document page = Jsoup.connect("https://example.com/").get();
try (OutputStream os = new FileOutputStream("example.pdf")) {
PdfRendererBuilder builder = new PdfRendererBuilder();
builder.withW3cDocument(new W3CDom().fromJsoup(page), page.location());
builder.toStream(os);
builder.run();
}
}
}This works for simple pages. openhtmltopdf doesn’t run JavaScript and doesn’t support flexbox or grid, so a modern site comes out with its columns stacked one above the other. Use Playwright for those.
Our Java PDF templates guide takes openhtmltopdf further: a Thymeleaf invoice template with page numbers, repeating table headers and custom fonts.
iText pdfHTML
iText is a full PDF library, and its pdfHTML add-on converts HTML and CSS to PDF. Of the four Java engines here, it had the most complete CSS support in our tests: it laid out flexbox and grid, which the other three stack vertically, and it accepted HTML that isn’t well-formed. iText is dual-licensed, AGPL v3 or a commercial licence.
pdfHTML is a separate artifact from iText’s core, which is a common source of “class not found” errors:
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>html2pdf</artifactId>
<version>6.3.4</version>
</dependency>Generate PDF from custom HTML content
import com.itextpdf.html2pdf.HtmlConverter;
import java.io.FileOutputStream;
public class ItextExample {
public static void main(String[] args) throws Exception {
String html = "<h1 style='color:#2563eb'>Invoice INV-1001</h1><p>Total: $250.00</p>";
HtmlConverter.convertToPdf(html, new FileOutputStream("invoice.pdf"));
}
}Generate PDF from a website URL
import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URI;
public class ItextFromUrl {
public static void main(String[] args) throws Exception {
String url = "https://example.com/";
// The base URI lets pdfHTML resolve the page's relative images and stylesheets
ConverterProperties properties = new ConverterProperties().setBaseUri(url);
try (InputStream html = URI.create(url).toURL().openStream()) {
HtmlConverter.convertToPdf(html, new FileOutputStream("example.pdf"), properties);
}
}
}Pass the page’s address as the base URI so pdfHTML can load its relative images and stylesheets. Like the other Java engines, pdfHTML doesn’t run the page’s JavaScript.
Flying Saucer
Flying Saucer is the original Java renderer for XHTML and CSS 2.1, and openhtmltopdf started as a fork of it. Current versions draw the PDF with OpenPDF and need Java 21 or newer. It is licensed LGPL 2.1 or later.
<dependency>
<groupId>org.xhtmlrenderer</groupId>
<artifactId>flying-saucer-pdf</artifactId>
<version>10.7.0</version>
</dependency>
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.24.1</version>
</dependency>Generate PDF from custom HTML content
import org.jsoup.Jsoup;
import org.jsoup.helper.W3CDom;
import org.xhtmlrenderer.pdf.ITextRenderer;
import java.io.FileOutputStream;
import java.io.OutputStream;
public class FlyingSaucerExample {
public static void main(String[] args) throws Exception {
String html = "<h1>Invoice INV-1001</h1><p>Total: $250.00<br>Due in 30 days</p>";
// Flying Saucer needs XHTML, so let jsoup fix up the markup first
org.w3c.dom.Document document = new W3CDom().fromJsoup(Jsoup.parse(html));
try (OutputStream os = new FileOutputStream("invoice.pdf")) {
ITextRenderer renderer = new ITextRenderer();
renderer.setDocument(document, null);
renderer.layout();
renderer.createPDF(os);
}
}
}Flying Saucer only accepts well-formed XHTML, so the example runs the markup through jsoup first; otherwise the unclosed <br> would stop it. Without an @page rule, the page size is US Letter.
For a website URL, use the jsoup approach from the openhtmltopdf example: Jsoup.connect(url).get(), then renderer.setDocument(new W3CDom().fromJsoup(page), page.location()).
OpenPDF
OpenPDF is an open-source PDF library, licensed LGPL 2.1 and MPL 2.0. Its core builds PDFs from Java objects such as Document and Paragraph. For HTML, OpenPDF 3 adds the openpdf-html module, a renderer based on Flying Saucer that also parses ordinary HTML, so the markup doesn’t need to be XHTML. OpenPDF 3 needs Java 21 or newer, and it renamed its packages from com.lowagie to org.openpdf, so code written for OpenPDF 1 or 2 needs new imports.
<dependency>
<groupId>com.github.librepdf</groupId>
<artifactId>openpdf-html</artifactId>
<version>3.0.5</version>
</dependency>Generate PDF from custom HTML content
import org.openpdf.pdf.ITextRenderer;
import java.io.FileOutputStream;
import java.io.OutputStream;
public class OpenPdfExample {
public static void main(String[] args) throws Exception {
String html = "<h1>Invoice INV-1001</h1><p>Total: $250.00<br>Due in 30 days</p>";
try (OutputStream os = new FileOutputStream("invoice.pdf")) {
ITextRenderer renderer = new ITextRenderer();
renderer.setDocumentFromString(html);
renderer.layout();
renderer.createPDF(os);
}
}
}Our OpenPDF guide walks through the setup step by step.
Playwright for Java
Playwright controls a real Chromium browser, so it renders whatever Chrome can: JavaScript, web fonts, flexbox and grid. That makes it the right tool for converting a live web page, or HTML built with a JavaScript framework. The cost is the browser: Playwright downloads one on first run, and each conversion uses far more memory than the Java engines. It is licensed Apache 2.0.
<dependency>
<groupId>com.microsoft.playwright</groupId>
<artifactId>playwright</artifactId>
<version>1.65.1</version>
</dependency>Generate PDF from a website URL
import com.microsoft.playwright.Browser;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.Playwright;
import com.microsoft.playwright.options.Margin;
import com.microsoft.playwright.options.WaitUntilState;
import java.nio.file.Paths;
public class PlaywrightExample {
public static void main(String[] args) {
try (Playwright playwright = Playwright.create()) {
Browser browser = playwright.chromium().launch();
Page page = browser.newPage();
page.navigate("https://en.wikipedia.org/wiki/PDF",
new Page.NavigateOptions().setWaitUntil(WaitUntilState.NETWORKIDLE));
page.pdf(new Page.PdfOptions()
.setPath(Paths.get("webpage.pdf"))
.setFormat("A4")
.setPrintBackground(true)
.setMargin(new Margin().setTop("20mm").setBottom("20mm")));
}
}
}For an HTML string, call page.setContent(html) instead of navigate. PDF output only works with Chromium, not Firefox or WebKit. Our Playwright and Java guide has a full walkthrough.
Comparison of the libraries
We ran the same test page through each library: a flexbox row, a CSS grid, a page-number footer, and a version of the page with unclosed tags and unquoted attributes.
| Criterion | openhtmltopdf | iText pdfHTML | Flying Saucer | OpenPDF (openpdf-html) | Playwright |
|---|---|---|---|---|---|
| Rendering | Own layout engine, drawn with PDFBox | Own layout engine | Own layout engine, drawn with OpenPDF | Flying Saucer-based, drawn with OpenPDF | Chromium browser |
| License | LGPL 2.1+ | AGPL v3 or commercial | LGPL 2.1+ | LGPL 2.1 / MPL 2.0 | Apache 2.0 |
| Input | Well-formed XHTML (clean HTML with jsoup) | HTML or XHTML | Well-formed XHTML (clean HTML with jsoup) | HTML or XHTML | Any web page |
| JavaScript | No | No | No | No | Yes |
| Flexbox and grid | No | Yes | No | No | Yes |
| Page numbers | Yes, CSS counter(page) | Yes, CSS counter(page) | Yes, CSS counter(page) | Yes, CSS counter(page) | Yes, header and footer templates |
| Maven artifact | io.github.openhtmltopdf:openhtmltopdf-pdfbox | com.itextpdf:html2pdf | org.xhtmlrenderer:flying-saucer-pdf | com.github.librepdf:openpdf-html | com.microsoft.playwright:playwright |
| Version tested | 1.1.114 | 6.3.4 | 10.7.0 | 3.0.5 | 1.65.1 |
| Minimum Java | 8 | 8 | 21 | 21 | 8 |
| Best for | Invoices, reports and templates | Complex CSS, or projects that can buy a licence | Existing Flying Saucer code | Projects already using OpenPDF | Live web pages and JavaScript |
Converting HTML to PDF using APITemplate.io
The examples above demonstrate how Java libraries can be used to convert HTML and web pages to PDF. However, generating PDFs using templates or keeping track of generated PDFs requires additional work. A PDF generator tracker is necessary to manage the files generated. If custom templates such as invoice generators are desired, they must also be created and managed.
APITemplate.io offers an HTML to PDF API that’s ideal for all those needs. Also, we use a chromium-based PDF renderer that fully supports HTML, content, and CSS.

Let’s see how we can use APITemplate.io to generate PDFs.
i. Generate PDF from Predefined Template
APITemplate.io allows you to manage your templates. Go to “Manage Templates” from the dashboard.

From Manage Template, you can create your own templates. The following is a sample invoice template. There are many templates available that you can choose from and customize based on your requirements.

To start using APITemplate.io APIs, you need to obtain your API Key, which can be obtained from the API Integration tab.

Now that you have your APITemplate account ready, let’s take some action and integrate it with our application. We will use the template to generate PDFs.
import okhttp3.*;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{\n \"date\": \"15/05/2022\",\n \"invoice_no\": \"435568799\",\n \"sender_address1\": \"3244 Jurong Drive\",\n \"sender_address2\": \"Falmouth Maine 1703\",\n \"sender_phone\": \"255-781-6789\",\n \"sender_email\": \"hello@logos.com\",\n \"rece_addess1\": \"2354 Lakeside Drive\",\n \"rece_addess2\": \"New York 234562\",\n \"rece_phone\": \"34333-84-223\",\n \"rece_email\": \"business@apitemplate.io\",\n \"items\": [\n {\"item_name\": \"Oil\", \"unit\": 1, \"unit_price\": 100, \"total\": 100},\n {\"item_name\": \"Rice\", \"unit\": 2, \"unit_price\": 200, \"total\": 400},\n {\"item_name\": \"Mangoes\", \"unit\": 3, \"unit_price\": 300, \"total\": 900},\n {\"item_name\": \"Cloth\", \"unit\": 4, \"unit_price\": 400, \"total\": 1600},\n {\"item_name\": \"Orange\", \"unit\": 7, \"unit_price\": 20, \"total\": 1400},\n {\"item_name\": \"Mobiles\", \"unit\": 1, \"unit_price\": 500, \"total\": 500},\n {\"item_name\": \"Bags\", \"unit\": 9, \"unit_price\": 60, \"total\": 5400},\n {\"item_name\": \"Shoes\", \"unit\": 2, \"unit_price\": 30, \"total\": 60}\n ],\n \"total\": \"total\",\n \"footer_email\": \"hello@logos.com\"\n}");
Request request = new Request.Builder()
.url("https://rest.apitemplate.io/v2/create-pdf?template_id=YOUR_TEMPLATE_ID")
.method("POST", body)
.addHeader("X-API-KEY", "YOUR_API_KEY")
.addHeader("Content-Type", "application/json")
.build();
Response response = null;
try {
response = client.newCall(request).execute();
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
System.err.println("Error: " + e.getMessage());
}
}
}And if we check the response_string, we have the following:
{
"download_url":"PDF_URL",
"transaction_ref":"8cd2aced-b2a2-40fb-bd45-392c777d6f6",
"status":"success",
"template_id":"YOUR_TEMPLATE_ID"
}In the above code, it’s very easy to use ApiTemplate to convert HTML to PDF because we don’t need to install any other library. We just need to call one simple API and use our data as a request body, and that’s it!
You can use the download_url from the response to download or distribute the generated PDF.
ii. Generate PDF from Website URL
ApiTemplate also supports generating PDFs from website URLs.
import okhttp3.*;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
MediaType mediaType = MediaType.parse("application/json");
String customHeaderFooterStyle = "<style>#header, #footer { padding: 0 !important; }</style>" +
"<table style=\"width: 100%; padding: 0px 5px;margin: 0px!important;font-size: 15px\">" +
"<tr>" +
"<td style=\"text-align:left; width:30%!important;\"><span class=\"date\"></span></td>" +
"<td style=\"text-align:center; width:30%!important;\"><span class=\"pageNumber\"></span></td>" +
"<td style=\"text-align:right; width:30%!important;\"><span class=\"totalPages\"></span></td>" +
"</tr>" +
"</table>";
RequestBody body = RequestBody.create(mediaType, "{\n" +
" \"url\": \"https://en.wikipedia.org/wiki/Sceloporus_malachiticus\",\n" +
" \"settings\": {\n" +
" \"paper_size\": \"A4\",\n" +
" \"orientation\": \"1\",\n" +
" \"header_font_size\": \"9px\",\n" +
" \"margin_top\": \"40\",\n" +
" \"margin_right\": \"10\",\n" +
" \"margin_bottom\": \"40\",\n" +
" \"margin_left\": \"10\",\n" +
" \"print_background\": \"1\",\n" +
" \"displayHeaderFooter\": true,\n" +
" \"custom_header\": \"" + customHeaderFooterStyle + "\",\n" +
" \"custom_footer\": \"" + customHeaderFooterStyle + "\"\n" +
" }\n" +
"}");
Request request = new Request.Builder()
.url("https://rest.apitemplate.io/v2/create-pdf-from-url")
.method("POST", body)
.addHeader("X-API-KEY", "YOUR_API_KEY")
.build();
Response response = null;
try {
response = client.newCall(request).execute();
System.out.println("PDF generated successfully: " + response.body().string());
} catch (IOException e) {
e.printStackTrace();
System.err.println("Error: " + e.getMessage());
}
}
}In the above code, we can provide the URL in the request body along with the settings for the PDF. APITemplate will use this request body to generate a PDF and return a download URL for your PDF.
iii. Generate PDF from Custom HTML Content
If you want to generate PDFs using your own custom HTML content, ApiTemplate also supports that.
import okhttp3.*;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
MediaType mediaType = MediaType.parse("application/json");
String customHeaderFooterStyle = "<style>#header, #footer { padding: 0 !important; }</style>" +
"<table style=\"width: 100%; padding: 0px 5px;margin: 0px!important;font-size: 15px\">" +
"<tr>" +
"<td style=\"text-align:left; width:30%!important;\"><span class=\"date\"></span></td>" +
"<td style=\"text-align:center; width:30%!important;\"><span class=\"pageNumber\"></span></td>" +
"<td style=\"text-align:right; width:30%!important;\"><span class=\"totalPages\"></span></td>" +
"</tr>" +
"</table>";
RequestBody body = RequestBody.create(mediaType, "{\n" +
" \"body\": \"<h1> hello world {{name}} </h1>\",\n" +
" \"css\": \"<style>.bg{background: red};</style>\",\n" +
" \"data\": {\n" +
" \"name\": \"This is a title\"\n" +
" },\n" +
" \"settings\": {\n" +
" \"paper_size\": \"A4\",\n" +
" \"orientation\": \"1\",\n" +
" \"header_font_size\": \"9px\",\n" +
" \"margin_top\": \"40\",\n" +
" \"margin_right\": \"10\",\n" +
" \"margin_bottom\": \"40\",\n" +
" \"margin_left\": \"10\",\n" +
" \"print_background\": \"1\",\n" +
" \"displayHeaderFooter\": true,\n" +
" \"custom_header\": \"" + customHeaderFooterStyle + "\",\n" +
" \"custom_footer\": \"" + customHeaderFooterStyle + "\"\n" +
" }\n" +
"}");
Request request = new Request.Builder()
.url("https://rest.apitemplate.io/v2/create-pdf-from-html")
.method("POST", body)
.addHeader("X-API-KEY", "YOUR_API_KEY")
.build();
Response response = null;
try {
response = client.newCall(request).execute();
System.out.println("PDF generated successfully: " + response.body().string());
} catch (IOException e) {
e.printStackTrace();
System.err.println("Error: " + e.getMessage());
}
}
}Similar to generating a PDF from a website URL, the API request above takes the body and CSS as part of the payload to generate a PDF.
Performance Considerations
When generating PDFs from HTML content, using open-source third-party libraries can work well in most cases. However, when it comes to scaling and handling edge cases, you need to handle those issues yourself.
This is where APITemplate.io comes in handy. It eliminates the need to worry about performance or scaling issues as it manages them for you. Even error situations are handled by APITemplate.io.
Conclusion
PDF generation is a common requirement in Java applications, and the right library depends on the HTML you start from. For documents you design yourself, openhtmltopdf is the usual choice, and it is also how you convert HTML to PDF with Apache PDFBox. iText pdfHTML handles more modern CSS if its licence suits you. Flying Saucer and OpenPDF fit projects that already use them. For live web pages and JavaScript, use Playwright.
For managing templates and generating PDFs through simple API calls, APITemplate.io is the hosted alternative.
Sign up for a free account with us now and start automating your PDF generation.
FAQ
How do I convert HTML to PDF with Apache PDFBox?
PDFBox can’t do it on its own: it creates and edits PDF files, but it has no HTML or CSS layout engine. Use openhtmltopdf, which lays out the HTML and draws it with PDFBox. Add io.github.openhtmltopdf:openhtmltopdf-pdfbox, then pass your HTML to PdfRendererBuilder.withHtmlContent().
What is the best Java library to convert HTML to PDF?
For invoices, reports and other documents you control, openhtmltopdf is the most common choice: free, maintained, and good at print CSS. iText pdfHTML supports more modern CSS, but it needs a commercial licence for closed-source software. For live web pages or JavaScript, use Playwright.
Which Java HTML to PDF libraries are free for commercial use?
openhtmltopdf and Flying Saucer are LGPL, OpenPDF is LGPL or MPL, and Playwright is Apache 2.0. All four can be used in closed-source commercial software, as long as you meet the licence’s conditions, such as letting users replace an LGPL library with their own version. iText is AGPL: unless you buy a commercial licence, you have to release your application’s source code, including when users only reach it over a network.
Why does my HTML fail with a SAXParseException?
openhtmltopdf and Flying Saucer parse their input as XML, so any unclosed tag (<br>, <img>) or unquoted attribute fails. Parse the HTML with jsoup and pass the result through new W3CDom().fromJsoup(document), as in the examples above.
Can Java convert a URL to PDF?
Yes. For most pages, use Playwright: it loads the page in Chromium, runs its JavaScript and prints it. For simple, static pages, you can fetch the HTML with jsoup and convert it with openhtmltopdf, Flying Saucer or iText.
Libraries:


