Java PDF Generation: Create PDFs From Templates (Thymeleaf + openhtmltopdf)
1. Introduction
Creating PDF documents programmatically is a common requirement in software development, especially when dealing with report generation, invoicing, or any content that requires a printable or easily distributable format.
The most maintainable way to do it in Java is to treat each document as a web page: design it once as an HTML template, fill the template with data at runtime, and render the result to PDF. Designers can edit the layout in HTML and CSS, and your code only deals with data.

This guide builds a PDF invoice that way, with two open-source libraries:
- Thymeleaf, the template engine Spring Boot uses, fills the HTML template with your data.
- openhtmltopdf renders the HTML and CSS to PDF, drawing it with Apache PDFBox.
Every example was compiled and run in November 2026 with Thymeleaf 3.1.7 and openhtmltopdf 1.1.114.
2. Add the Dependencies
Add both libraries to your pom.xml:
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf</artifactId>
<version>3.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>io.github.openhtmltopdf</groupId>
<artifactId>openhtmltopdf-pdfbox</artifactId>
<version>1.1.114</version>
</dependency>Two things have changed since most openhtmltopdf tutorials were written. The project moved to the io.github.openhtmltopdf group: the old com.openhtmltopdf artifacts stopped at version 1.0.10 in 2021. And the useFastMode() call those tutorials include is now deprecated, because the fast renderer is the default.
3. Write the Invoice Template
Save the template as src/main/resources/templates/invoice.html:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<style>
@page {
size: A4;
margin: 20mm 15mm;
@bottom-center {
content: "Page " counter(page) " of " counter(pages);
font-size: 9pt;
}
}
body { font-family: sans-serif; font-size: 11pt; }
/* -fs-table-paginate repeats the header row on every page */
table { width: 100%; border-collapse: collapse; -fs-table-paginate: paginate; }
th, td { padding: 6px; border-bottom: 1px solid #ddd; text-align: left; }
tr { page-break-inside: avoid; }
.total { text-align: right; font-weight: bold; }
</style>
</head>
<body>
<h1>Invoice <span th:text="${invoice.number}">INV-0000</span></h1>
<p>Bill to: <span th:text="${invoice.customer}">Customer name</span></p>
<table>
<thead>
<tr><th>Item</th><th>Qty</th><th>Price</th></tr>
</thead>
<tbody>
<tr th:each="item : ${invoice.items}">
<td th:text="${item.name}">Item</td>
<td th:text="${item.qty}">1</td>
<td th:text="${#numbers.formatDecimal(item.price, 1, 2)}">0.00</td>
</tr>
</tbody>
</table>
<p class="total">Total: <span th:text="${#numbers.formatDecimal(invoice.total, 1, 2)}">0.00</span></p>
</body>
</html>How the template works:
th:textreplaces the sample text with a value, so the file still opens in a browser as a preview.th:eachrepeats the table row once per item, and#numbers.formatDecimalformats the prices with two decimals.- The
@pagerule sets the paper size and margins. Its@bottom-centerbox prints “Page 1 of 3” at the bottom of every page. -fs-table-paginate: paginaterepeats the table’s header row on every page. It is an openhtmltopdf property; in our tests,display: table-header-groupalone did not repeat the header.page-break-inside: avoidkeeps a row from being split across two pages.
openhtmltopdf reads its input as XML, so the template must be well-formed: close every tag, including empty ones like <meta ... /> and <img ... />.
4. Fill the Template and Render the PDF
import com.openhtmltopdf.pdfboxout.PdfRendererBuilder;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.List;
public class InvoicePdf {
public record Item(String name, int qty, double price) {}
public record Invoice(String number, String customer, List<Item> items) {
public double total() {
return items.stream().mapToDouble(i -> i.qty() * i.price()).sum();
}
}
public static void main(String[] args) throws Exception {
// 1. Find templates in src/main/resources/templates/
ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver();
resolver.setPrefix("templates/");
resolver.setSuffix(".html");
resolver.setTemplateMode(TemplateMode.HTML);
resolver.setCharacterEncoding("UTF-8");
TemplateEngine engine = new TemplateEngine();
engine.setTemplateResolver(resolver);
// 2. Fill the template with data
Invoice invoice = new Invoice("INV-1001", "Acme Corp", List.of(
new Item("Design work", 10, 85.00),
new Item("Hosting (12 months)", 1, 240.00)));
Context context = new Context();
context.setVariable("invoice", invoice);
String html = engine.process("invoice", context);
// 3. Render the HTML to PDF. The base URI resolves relative images and CSS.
String baseUri = InvoicePdf.class.getResource("/templates/").toString();
try (OutputStream os = new FileOutputStream("invoice.pdf")) {
PdfRendererBuilder builder = new PdfRendererBuilder();
builder.withHtmlContent(html, baseUri);
builder.toStream(os);
builder.run();
}
}
}The code does three things:
- Finds the template. The
ClassLoaderTemplateResolverloadsinvoice.htmlfrom thetemplatesfolder on the classpath. - Fills it with data. Thymeleaf reads Java records directly:
${invoice.number}callsinvoice.number(), and${invoice.total}calls thetotal()method.engine.processreturns the finished HTML as a string. - Renders the PDF.
PdfRendererBuilderlays out the HTML and writes the PDF. The base URI points at the templates folder, so an<img src="logo.png" />in the template loadstemplates/logo.png.
With two items the invoice fits on one page. In our test with 60 items it ran to three pages, each with the column headers repeated at the top and “Page 1 of 3”, “Page 2 of 3” and so on at the bottom.
5. Use Your Own Fonts
By default openhtmltopdf uses the standard PDF fonts (Helvetica, Times and Courier), which only cover Western European characters. To use your brand font, or to print other scripts, register a TrueType file before calling run():
builder.useFont(new File("fonts/DejaVuSans.ttf"), "DejaVu Sans");Then use the same family name in the template’s CSS:
body { font-family: "DejaVu Sans", sans-serif; }openhtmltopdf embeds the font in the PDF, so it looks the same on every device.
6. Using It With Spring Boot
With spring-boot-starter-thymeleaf on the classpath, Spring Boot creates a TemplateEngine that already reads templates from src/main/resources/templates/. Inject it, and the template resolver setup from step 4 goes away:
import com.openhtmltopdf.pdfboxout.PdfRendererBuilder;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@Service
public class InvoicePdfService {
private final TemplateEngine templateEngine;
public InvoicePdfService(TemplateEngine templateEngine) {
this.templateEngine = templateEngine;
}
public byte[] render(InvoicePdf.Invoice invoice) throws IOException {
Context context = new Context();
context.setVariable("invoice", invoice);
String html = templateEngine.process("invoice", context);
ByteArrayOutputStream out = new ByteArrayOutputStream();
PdfRendererBuilder builder = new PdfRendererBuilder();
builder.withHtmlContent(html, getClass().getResource("/templates/").toString());
builder.toStream(out);
builder.run();
return out.toByteArray();
}
}To return the PDF from a controller, send the bytes with the application/pdf content type.
7. Other Ways to Generate PDFs in Java
openhtmltopdf is the most common choice for templates, but not the only one:
- iText pdfHTML supports more modern CSS, including flexbox and grid, but it is AGPL, so closed-source software needs a commercial licence.
- Flying Saucer and OpenPDF’s
openpdf-htmlmodule work much like openhtmltopdf, drawing with OpenPDF instead of PDFBox. - Playwright for Java prints with a real Chromium browser, for pages that need JavaScript.
Our HTML to PDF in Java comparison shows each of them with tested code and a side-by-side table.
OpenPDF vs PDFBox: both are lower-level PDF libraries rather than HTML renderers. OpenPDF, a fork of iText 4, builds documents from Java objects such as Paragraph and Table. Apache PDFBox draws text and shapes at page coordinates, and is strong at reading, editing and extracting text from existing PDFs. For HTML templates, you use either one through a renderer: openhtmltopdf on PDFBox, or openpdf-html on OpenPDF.
8. Conclusion
An HTML template filled by Thymeleaf and rendered by openhtmltopdf gives you PDFs whose layout lives in HTML and CSS, where it is easy to change, while your Java code only supplies the data. Print CSS covers what business documents need: page sizes, page numbers and table headers that repeat on every page.
If you would rather not run the rendering yourself, APITemplate.io works the same way as a hosted service. You design the template in an HTML or visual editor, and your Java code sends JSON to the PDF generation API and gets a PDF back.
Sign up for a free account with APITemplate.io now and start automating your PDF generation.


