pdforge logo

pdforge

Product

Resources

Integrations

PDF Libraries

PDF Libraries

Java

Java

How to Generate PDF from HTML with Playwright using Java (Updated 2025)

Marcelo Abreu, founder of pdforge

Marcelo | Founder

Marcelo | Founder

Aug 6, 2025

Aug 6, 2025

What is Playwright and How Can It Generate PDFs from HTML?

Playwright is a versatile, open-source automation toolkit explicitly designed for browser tasks, such as testing, web scraping, and PDF document generation. Supporting browsers like Chromium, Firefox, and WebKit, Playwright ensures consistent rendering across platforms. Java developers frequently leverage Playwright for its efficient APIs, remarkable speed, and outstanding support for dynamic web content.

When converting HTML to PDF, Playwright distinguishes itself by faithfully capturing everything the browser renders—from intricate CSS to JavaScript-generated content. This capability guarantees precision-perfect PDF documents, ideal for SaaS reports, dynamic invoices, or complex documentation.

Extensive and accessible documentation further simplifies Playwright’s integration into Java applications, streamlining troubleshooting and reducing development time.


If you're using other programming languages, check out our other guides:

Alternative Java PDF Libraries: Why Playwright Stands Out

The Java ecosystem offers several noteworthy PDF libraries:

  • iText: Robust PDF manipulation and generation, but limited native HTML rendering capability.

  • Flying Saucer: Excellent CSS rendering but struggles significantly with JavaScript-rich content.

  • Apache PDFBox: Powerful for PDF manipulation but not optimized for HTML-to-PDF conversions.

  • OpenPDF: A derivative of iText, offering similar functionalities with an open-source license. It shares the complexities of iText without full support for advanced HTML content.

Compared to these options, Playwright uniquely integrates robust JavaScript rendering, seamless browser interactions, and comprehensive support for HTML-to-PDF workflows, making it the ideal PDF library for Java.

If you want to go deep on a full comparison between pdf libraries in JAVA for 2025, you can check out this guide.

Guide to generate pdf from html using Java Playwright
Guide to generate pdf from html using Java Playwright

Step 01: Setting Up Playwright for HTML-to-PDF Conversion in Java

First, ensure your Java Development Kit (JDK) is installed from jdk.java.net or oracle.com/java.

Include Playwright in your Maven or Gradle build configuration:

For Maven:

<dependency>
    <groupId>com.microsoft.playwright</groupId>
    <artifactId>playwright</artifactId>
    <version>1.45.0</version>
</dependency

For Gradle:

Step 02: Generating Your First PDF Using Playwright in Java

Using Playwright to create PDFs from Java is straightforward. Here’s how you can begin:

Alternative 01: Generate PDF from a URL

Generate a PDF document directly from a webpage URL:

import com.microsoft.playwright.*;

public class GeneratePdfFromUrl {
    public static void main(String[] args) {
        try (Playwright playwright = Playwright.create()) {
            Browser browser = playwright.chromium().launch();
            Page page = browser.newPage();
            page.navigate("https://example.com");
            page.pdf(new Page.PdfOptions().setPath("example.pdf").setFormat("A4"));
        }
    }
}

This Java snippet:

  • Opens a headless Chromium browser

  • Navigates to the specified URL

  • Saves the rendered page as a PDF

Alternative 02: Generate PDF from an HTML String

To create PDFs directly from raw HTML:

import com.microsoft.playwright.*;

public class GeneratePdfFromHtmlString {
    public static void main(String[] args) {
        try (Playwright playwright = Playwright.create()) {
            Browser browser = playwright.chromium().launch();
            Page page = browser.newPage();
            String html = "<html><body><h1>Hello, PDF!</h1></body></html>";
            page.setContent(html);
            page.pdf(new Page.PdfOptions().setPath("sample.pdf").setFormat("Letter"));
        }
    }
}

Configuring Playwright PDF Options (Headers, Footers, Margins)

Playwright provides comprehensive configuration options to customize PDF documents:

page.pdf(new Page.PdfOptions()
    .setPath("custom.pdf")
    .setFormat("A4")
    .setMargin(new Page.Margin().setTop("20mm").setBottom("20mm"))
    .setDisplayHeaderFooter(true)
    .setHeaderTemplate("<span style='font-size:10px'>Header Content</span>")
    .setFooterTemplate("<span style='font-size:10px'>Page <span class='pageNumber'></span> of <span class='totalPages'></span></span>")
);

Check out further options in the official Playwright Java documentation.

Creating PDF Templates in Java using Template Engines

Java template engines such as Thymeleaf streamline HTML creation for dynamic content:

// Using Thymeleaf to generate dynamic HTML
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

TemplateEngine templateEngine = new TemplateEngine();
Context context = new Context();
context.setVariable("clientName", "Acme Inc.");

String htmlContent = templateEngine.process("<h1>Invoice for [[${clientName}]]</h1>", context);

page.setContent(htmlContent);
page.pdf(new Page.PdfOptions().setPath("invoice.pdf"));

Step 03: Scaling Playwright PDF Generation with Serverless Solutions

PDF rendering with Playwright can consume significant computational resources. Serverless architectures such as AWS Lambda or Google Cloud Functions are ideal for scaling efficiently.

To run Playwright within a serverless environment, browser engines like Chromium must be deployed as custom layers or via Docker containers, simplifying resource provisioning and scaling effectively.

We also have a comprehensive guide to deploying Playwright within AWS Lambda.

Alternative: Scale PDF Generation with Third-Party APIs

homepage of pdforge

For larger SaaS platforms requiring automated PDF generation at scale, if you're developing using no-code platforms like Bubble or creating automation workflows using platforms like n8n, make or zapier, integrating a PDF Generation API like pdforge can offload the heavy lifting.

With pdforge, you can create beautiful PDF documents in minutes using our AI-first PDF Generation. You can fine-tune de design with an easy-to-use opinionated no-code builder and start generating PDFs using our API or native integration with no-code tools. Let the AI do the heavy lifting by generating your templates, creating custom components or even filling all the variables for you.

You can handle high-volume PDF generation from a single backend call.

Here’s an example of how to generate pdf with pdforge via an API call:

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

URL url = new URL("https://api.pdforge.com/v1/pdf");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization", "Bearer YOUR_API_KEY");
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);

String jsonInput = "{\"templateId\":\"invoice-template\", \"data\":{\"client\":\"Acme Inc.\"}}";
try(OutputStream os = conn.getOutputStream()) {
    byte[] input = jsonInput.getBytes("utf-8");
    os.write(input, 0, input.length);
}

try(InputStream is = conn.getInputStream(); FileOutputStream fos = new FileOutputStream("invoice.pdf")) {
    byte[] buffer = new byte[1024];
    int bytesRead;
    while ((bytesRead = is.read(buffer)) != -1) {
        fos.write(buffer, 0, bytesRead);
    }
}

You can create your account, experience our no-code builder and create your first layout template without any upfront payment clicking here.

If you prefer a managed service, third-party APIs like pdforge offer scalable HTML-to-PDF generation without infrastructure setup or design changes management from you. These solutions manage everything from HTML template rendering to PDF delivery.

Conclusion

Playwright Java provides developers with a potent toolkit to generate pixel-perfect PDFs from HTML, making it the optimal choice for SaaS platforms and enterprise applications.

For those aiming to minimize infrastructure maintenance and rapidly scale their document generation, third-party PDF APIs like pdforge offer an efficient, manageable, and scalable solution.

Generating pdfs at scale can be annoying!

Generating pdfs at scale can be annoying!

Let us help you make it easier while you focus on what truly matters for your company.

Let us help you make it easier while you focus on what truly matters for your company.

7-day free trial

7-day free trial

Table of contents

Automate PDF Generation with pdforge

No code or design experience needed

AI creates your template in seconds

Fine tune the design in our no-code builder

Generate PDFs with our API or integrations