Course – LS – All
announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:


1. Overview

In this tutorial, we’ll learn how to generate PDFs using Thymeleaf as a template engine through a quick and practical example.

2. Maven Dependencies

First, let’s add our Thymeleaf dependency:


Thymeleaf by itself is just a template engine, and it can’t generate PDFs on its own. For this purpose, we’re going to add flying-saucer-pdf to our pom.xml:


3. Generating PDFs

Next, let’s create a simple Thymeleaf HTML template – thymeleaf_template.html:

<html xmlns:th="">
    <h3 style="text-align: center; color: green">
      <span th:text="'Welcome to ' + ${to} + '!'"></span>

And then, we’ll create a simple function – parseThymeleafTemplate – that’ll parse our template and return an HTML String:

private String parseThymeleafTemplate() {
    ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();

    TemplateEngine templateEngine = new TemplateEngine();

    Context context = new Context();
    context.setVariable("to", "Baeldung");

    return templateEngine.process("thymeleaf_template", context);

Finally, let’s implement a simple function that receives the previously generated HTML as input and write a PDF to our home folder:

public void generatePdfFromHtml(String html) {
    String outputFolder = System.getProperty("user.home") + File.separator + "thymeleaf.pdf";
    OutputStream outputStream = new FileOutputStream(outputFolder);

    ITextRenderer renderer = new ITextRenderer();


After running our code, we’ll notice a file named thymeleaf.pdf, in our user’s home directory, that looks like this:baeldung pdf

As we can see, the text is green and aligned to the center as defined in our inline CSS. This is an extremely powerful tool for customizing our PDFs.

We should keep in mind that Thymeleaf is completely decoupled from Flying Saucer, meaning that we can use any other template engine for creating PDFs like Apache FreeMarker.

4. Conclusion

In this quick tutorial, we’ve learned how to easily generate PDFs using Thymeleaf as a template engine.

As always, the code is available over on GitHub.

Partner – Expected Behavior – NPI (tag=PDF)
announcement - icon

Creating PDFs is actually surprisingly hard. When we first tried, none of the existing PDF libraries met our needs. So we made DocRaptor for ourselves and later launched it as one of the first HTML-to-PDF APIs.

We think DocRaptor is the fastest and most scalable way to make PDFs, especially high-quality or complex PDFs. And as developers ourselves, we love good documentation, no-account trial keys, and an easy setup process.

>> Try DocRaptor's HTML-to-PDF Java Client (No Signup Required)

Course – LS – All
announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:


res – REST with Spring (eBook) (everywhere)