Generating PDFs with Java
Java has the oldest and widest PDF ecosystem of any language: a low-level Apache library, two descendants of the original iText code base with very different licences, an HTML renderer that produces real PDF structure rather than screenshots, and a mature headless-Chromium driver. The choice turns on two questions: do you need a layout engine, and can your project live with AGPL.
## The options| Library | Approach | Licence | Maven coordinates | Best for | Avoid when |
|---|---|---|---|---|---|
| Apache PDFBox 3.0 | Low-level drawing with PDPageContentStream; reading, text extraction, forms, signatures; no layout engine | Apache-2.0 | org.apache.pdfbox:pdfbox:3.0.8 (Java 8) | Full control of the output, manipulating existing files, text extraction, permissive licence | You need paragraphs and tables that wrap and paginate themselves |
| OpenPDF 3.0 | Document model (Document, Paragraph, PdfPTable), descended from iText 4 | MPL-2.0 OR LGPL-2.1+ (dual); the html and renderer modules are LGPL-2.1 only | com.github.librepdf:openpdf:3.0.5 (Java 21; 2.0.x for Java 17, 1.4.x for Java 11) | Reports and documents with tables under a permissive licence; migrating iText 2/4 code | You need PDF 2.0 features, PDF/UA or modern signature support |
| iText 9 (iText Core) | Low-level kernel plus a layout module; forms, signatures, PDF/A, PDF/UA, tagging | AGPL-3.0 or commercial | com.itextpdf:itext-core:9.8.0 (type pom) plus com.itextpdf:bouncy-castle-adapter | The widest feature set; compliance work | Your source cannot be released under AGPL and no commercial licence is budgeted |
| OpenHTMLtoPDF 1.1 | HTML and CSS 2.1 renderer (plus some CSS 3 paged media) producing PDF through PDFBox | LGPL-2.1 or later | io.github.openhtmltopdf:openhtmltopdf-pdfbox:1.1.x (community fork of danfickle/openhtmltopdf) | Templated documents from XHTML without running a browser; PDF/A output | Templates rely on flexbox, grid or JavaScript, none of which it supports |
| Playwright for Java | Headless Chromium (HTML renderer) | Apache-2.0 | com.microsoft.playwright:playwright:1.64.0 | Documents that exist as web pages with modern CSS | Environments that cannot run a browser |
| JasperReports | Report engine with a visual designer and PDF export | LGPL-3.0 | net.sf.jasperreports:jasperreports | Data-bound reports designed by non-developers | Documents that are not reports |
| Apache FOP | XSL-FO formatter producing PDF | Apache-2.0 | org.apache.xmlgraphics:fop | XML pipelines that already produce XSL-FO; long technical manuals | Anyone who does not already write XSL-FO |
Two facts on this table are easy to get wrong. OpenPDF 3.0 renamed its packages from com.lowagie to org.openpdf, so code copied from older tutorials will not compile against 3.0.x without an import rewrite; the 2.1 line keeps the old names and needs Java 21, 2.0.x needs Java 17. And OpenHTMLtoPDF moved: the original com.openhtmltopdf artefacts stopped at 1.0.10 in the archived repository, and the community fork publishes under the group id io.github.openhtmltopdf with 1.1.x releases.
The developers hub compares drawing APIs, layout engines and HTML renderers in general terms. In Java the split is unusually clean: PDFBox draws, OpenPDF and iText lay out, OpenHTMLtoPDF and Playwright render HTML.
PDFBox: text with an embedded TrueType font#
PDFBox gives you a page and a content stream and nothing else: no paragraphs, no wrapping, no tables. In return you get exact control and a library that also reads, splits, merges, fills forms and extracts text. The one decision that matters on the first day is the font. PDType1Font with a Standard14Fonts.FontName uses the viewer's built-in Helvetica or Times and cannot embed; PDType0Font.load embeds a TrueType file as a subset and handles any Unicode text.
import java.io.File;
import java.io.IOException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDType0Font;
public final class DeliveryNote {
public static void main(String[] args) throws IOException {
try (PDDocument document = new PDDocument()) {
PDPage page = new PDPage(PDRectangle.A4);
document.addPage(page);
document.getDocumentInformation().setTitle("Delivery note 2026-0142");
// Embeds a subset of the TrueType file; works for any script the font covers.
PDType0Font font = PDType0Font.load(document, new File("fonts/NotoSans-Regular.ttf"));
try (PDPageContentStream stream = new PDPageContentStream(document, page)) {
stream.beginText();
stream.setFont(font, 18);
stream.setLeading(14f);
// PDF coordinates: origin bottom-left, points. A4 is 595 x 842 pt.
stream.newLineAtOffset(72, 770);
stream.showText("Delivery note 2026-0142");
stream.setFont(font, 11);
stream.newLine();
stream.showText("Shipped 29 October 2026 to Jaana Mäkelä, Køge");
stream.newLine();
stream.showText("Tiếng Việt and русский render because the font is embedded");
stream.endText();
stream.moveTo(72, 730);
stream.lineTo(523, 730);
stream.stroke();
}
document.save("delivery-note.pdf");
}
}
}setLeading and newLine move down by the leading from the current line start, which is the only line-breaking PDFBox offers; wrapping long text is your code, measuring with font.getStringWidth(text) / 1000 * size. In PDFBox 3.0 the standard-14 constants became new PDType1Font(Standard14Fonts.FontName.HELVETICA); the old static fields are gone, and instances are no longer singletons.
OpenPDF: a document with a table#
OpenPDF keeps the iText 2 and 4 programming model: a Document you open, add elements to, and close. PdfPTable wraps, splits across pages and repeats its header rows. The 3.0 line lives in the org.openpdf packages.
import java.io.FileOutputStream;
import org.openpdf.text.Document;
import org.openpdf.text.Font;
import org.openpdf.text.PageSize;
import org.openpdf.text.Paragraph;
import org.openpdf.text.pdf.BaseFont;
import org.openpdf.text.pdf.PdfPTable;
import org.openpdf.text.pdf.PdfWriter;
public final class Report {
public static void main(String[] args) throws Exception {
Document document = new Document(PageSize.A4, 56, 56, 56, 56);
PdfWriter.getInstance(document, new FileOutputStream("report.pdf"));
document.open();
// IDENTITY_H selects a composite font so any Unicode text can be shown; EMBEDDED subsets the file.
BaseFont base = BaseFont.createFont("fonts/NotoSans-Regular.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
Font title = new Font(base, 18, Font.BOLD);
Font body = new Font(base, 10);
document.add(new Paragraph("Quarterly summary", title));
PdfPTable table = new PdfPTable(new float[] {3, 1, 1});
table.setWidthPercentage(100);
table.setHeaderRows(1); // repeated on every page
table.addCell(new Paragraph("Region", body));
table.addCell(new Paragraph("Units", body));
table.addCell(new Paragraph("Revenue", body));
String[][] rows = {{"North", "1,204", "48,160.00"}, {"South", "980", "39,200.00"}};
for (String[] r : rows) {
for (String cell : r) table.addCell(new Paragraph(cell, body));
}
document.add(table);
document.close();
}
}The four numbers after PageSize.A4 are margins in points. If you are on Java 17, use OpenPDF 2.0.x and the com.lowagie.text package names; the API is otherwise the same.
OpenHTMLtoPDF: rendering XHTML with your own font#
OpenHTMLtoPDF lays out strict XHTML with CSS 2.1 and parts of CSS 3 paged media (@page, page breaks, running headers through margin boxes) and writes the result through PDFBox, so the output has real text, embedded subset fonts and, optionally, PDF/A conformance. It does not execute JavaScript and does not implement flexbox or grid; templates written for it look like 2010 CSS, and that is the trade for not running a browser.
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import com.openhtmltopdf.pdfboxout.PdfRendererBuilder;
public final class Render {
public static void main(String[] args) throws Exception {
String html = Files.readString(Path.of("templates/invoice.xhtml"), StandardCharsets.UTF_8);
// Base URI resolves relative images and stylesheets in the template.
String baseUri = Path.of("templates").toUri().toString();
try (OutputStream os = new FileOutputStream("invoice.pdf")) {
PdfRendererBuilder builder = new PdfRendererBuilder();
builder.withHtmlContent(html, baseUri);
// Register the font under the family name the CSS uses: font-family: "Noto Sans".
builder.useFont(new File("fonts/NotoSans-Regular.ttf"), "Noto Sans");
builder.toStream(os);
builder.run();
}
}
}Only fonts registered with useFont (or declared with @font-face pointing at a file) are available; there is no fallback to system fonts, which makes output identical across machines. useFastMode() appears in older tutorials and is deprecated since 1.0.11 because the fast renderer became the only renderer. The input must be well-formed XML; HTML with unclosed tags fails to parse, so run templates through an HTML-to-XHTML cleaner such as jsoup first.
iText 9: the layout module#
iText Core 9 is the most complete library here and the one with the most consequential licence. The kernel exposes every PDF object; the layout module adds Document, Paragraph, Table and Cell with wrapping and pagination; add-ons cover signatures, PDF/A, PDF/UA, forms and redaction. Since 8.0.2 the Bouncy Castle adapter is a separate dependency that encryption and signatures need at runtime.
import com.itextpdf.io.font.PdfEncodings;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.properties.UnitValue;
public final class Summary {
public static void main(String[] args) throws Exception {
try (Document document = new Document(new PdfDocument(new PdfWriter("summary.pdf")))) {
PdfFont font = PdfFontFactory.createFont("fonts/NotoSans-Regular.ttf", PdfEncodings.IDENTITY_H);
document.setFont(font).setFontSize(10);
document.add(new Paragraph("Quarterly summary").setFontSize(18));
Table table = new Table(UnitValue.createPercentArray(new float[] {3, 1, 1}))
.useAllAvailableWidth();
table.addHeaderCell("Region");
table.addHeaderCell("Units");
table.addHeaderCell("Revenue");
table.addCell("North").addCell("1,204").addCell("48,160.00");
table.addCell("South").addCell("980").addCell("39,200.00");
document.add(table);
}
}
}createPercentArray normalises the widths to 100 percent; header cells repeat at the top of every page the table spans. The Maven dependency is com.itextpdf:itext-core with type pom, which pulls in the kernel, layout, io and the other modules, plus com.itextpdf:bouncy-castle-adapter.
Headless Chromium with Playwright#
When the template needs modern CSS or must match a web page exactly, render it with Chromium. Playwright for Java downloads its own browser builds and exposes page.pdf with the same options as its other language bindings. The HTML-to-PDF guide covers print CSS, headers, footers and the security of rendering untrusted HTML; this is the Java side.
import java.nio.file.Paths;
import com.microsoft.playwright.Browser;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.Playwright;
import com.microsoft.playwright.options.Margin;
public final class Print {
public static void main(String[] args) {
try (Playwright playwright = Playwright.create()) {
Browser browser = playwright.chromium().launch();
Page page = browser.newPage();
page.navigate("http://127.0.0.1:8080/invoice/2026-0142");
page.pdf(new Page.PdfOptions()
.setPath(Paths.get("invoice.pdf"))
.setFormat("A4")
.setPrintBackground(true)
.setMargin(new Margin().setTop("20mm").setBottom("20mm").setLeft("15mm").setRight("15mm")));
}
}
}PDF generation is a Chromium-only feature in Playwright, and page.pdf uses the print media type by default, so @media print rules apply.
Traps specific to Java#
Standard 14 versus embedded fonts. PDType1Font with a standard-14 name, OpenPDF's FontFactory.getFont("Helvetica") and iText's StandardFonts.HELVETICA all produce a font that is not embedded and that encodes text as single bytes in WinAnsiEncoding. Any character outside that set fails: PDFBox throws an IllegalArgumentException naming the code point, OpenPDF silently drops or substitutes, iText throws. The fix is the same everywhere: load a TrueType or OpenType file (PDType0Font.load, BaseFont.createFont with IDENTITY_H, PdfFontFactory.createFont with IDENTITY_H) so the font is composite, Unicode-capable and embedded as a subset. The fonts page explains what simple and composite fonts are inside the file. Note that ISO 32000-2 (PDF 2.0) removed the standard-14 exemption entirely, so new code should embed in any case.
Fonts in containers. Embedding from a file path means the file must ship with the application. Put fonts on the classpath and load them from a stream (PDType0Font.load(document, inputStream), BaseFont.createFont from bytes, builder.useFont with a supplier) so a JAR deploys as a unit.
AGPL reach. iText Core is AGPL-3.0: any application that uses it and that users interact with, including over a network, must publish its source under the AGPL unless a commercial licence is held. "Internal" is not an exemption under the AGPL's network clause. OpenPDF exists because the iText 4 code base was still MPL/LGPL, and it remains the drop-in choice when the licence is the blocker.
Package renames. OpenPDF 3.0 uses org.openpdf; iText 7 and later use com.itextpdf with a different API from iText 5 (com.itextpdf.text). Code found on the web is often for the wrong one.
Coordinates. PDFBox and iText's kernel canvas use the PDF coordinate system: origin at the bottom-left, units of 1/72 inch, as described on the units page. OpenPDF and iText's layout module hide that behind margins and flowing elements, but their absolute-positioning calls use the same origin.
Metadata and producer strings. Each library writes its own /Producer and, by default, no title. Set the document information explicitly (PDFBox getDocumentInformation(), OpenPDF document.addTitle, iText getDocumentInfo()); the metadata page shows where those values land and how XMP differs from the Info dictionary.
Versions. PDFBox 2.0.37 is still maintained alongside 3.0.8 and has a different font API (static PDType1Font.HELVETICA); the 3.0 migration guide lists the changes. OpenHTMLtoPDF 1.1.x requires PDFBox 3; mixing it with a project pinned to PDFBox 2 fails at class loading.
Sources
- Apache PDFBox downloads (3.0.8, 2.0.37) and 3.0 migration guide
- PDFBox examples, HelloWorld.java (standard 14 font) and EmbeddedFonts.java (PDType0Font.load)
- OpenPDF repository (3.0.5, Java 21, MPL-2.0 OR LGPL-2.1+, org.openpdf package rename)
- OpenPDF PdfWriter source (package org.openpdf.text.pdf, getInstance)
- OpenHTMLtoPDF community repository (LGPL-2.1 or later, CSS 2.1 layout)
- OpenHTMLtoPDF on Maven Central (io.github.openhtmltopdf:openhtmltopdf-pdfbox)
- OpenHTMLtoPDF integration guide (PdfRendererBuilder usage)
- iText for Java repository (AGPL/commercial, Maven coordinates)
- iText layout Table and UnitValue sources
- Playwright for Java, getting started (Maven coordinates, Playwright.create)
- Playwright for Java repository (Apache-2.0)
- JasperReports repository (LGPL-3.0)
- Apache FOP