pdforge logo

Product

Resources

Integrations

pdforge logo

Redirected from pdforge.com? You’re in the right place. we’re now pdf noodle!

Redirected from pdforge.com? You’re in the right place. we’re now pdf noodle!

Redirected from pdforge.com? You’re in the right place. we’re now pdf noodle!

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

Written by

Written by

Marcelo Abreu, founder of pdforge

Marcelo | Founder of pdf noodle

Marcelo | Founder of pdf noodle

Last Updated

Last Updated

Aug 6, 2025

Aug 6, 2025

Tags

Tags

PDF Libraries

PDF Libraries

Java

Java

pdforge logo
pattern behind Call to action

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
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: Convert HTML to PDF Using pdf noodle

Homepage of pdf noodle

Managing HTML-to-PDF conversion at scale can quickly become a nightmare!

Especially in serverless environments where cold starts, memory limits, and headless browser quirks love to break at the worst possible time (we even wrote a full article about it). Add constant template iterations, version control headaches, and the need to support non-technical contributors, and suddenly your “simple PDF library” turns into an ongoing engineering project.

pdf noodle eliminates all of that.

Instead of maintaining brittle infrastructure or wrestling with outdated pdf libraries, pdf noodle gives you a battle-tested PDF generation API that just works!

Fast, scalable, and designed for both developers and non-developers. You send raw HTML or use our AI-powered template builder, and pdf noodle handles the rendering, scaling, optimization, and delivery so your team doesn’t have to.

Here's an example of a simple API request to generate your pixel-perfect PDF with just a few lines of code:

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

public class PdfForgeExample {
    public static void main(String[] args) {
        try {
            URL url = new URL("https://api.pdfnoodle.com/v1/html-to-pdf/sync");
            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 jsonInputString = " { \"html\": \"your-html\" }";

            try(OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream())) {
                writer.write(jsonInputString);
                writer.flush();
            }

            int responseCode = conn.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // Read the response and process the PDF
            } else {
                // Handle errors
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

pdf noodle also includes a powerful AI Agent that can generate PDF templates instantly, along with a modern editor for refining the design, also using AI, to match your brand. You don't need developing or design experience to quickly update layouts, adjust styling, and manage template versions.

Here’s a quick demo showing how it works:

You can create your account and design your first template without any upfront payment.

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.

If you don't want to waste time maintaining pdfs layouts and their infrastructure or if you don't want to keep track of best practices to generate PDFs at scale, third-party PDF APIs like pdf noodle will save you hours of work and deliver a high quality pdf layout.

Generating pdfs can be annoying!

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

pdforge logo
pattern behind Call to action

Generating pdfs can be annoying!

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

pdforge logo
pattern behind Call to action

Generating pdfs can be annoying!

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

pdforge logo
pattern behind Call to action

Table of contents

Automate PDF Generation in minutes

No code or design experience needed

AI creates your template in seconds

Fine tune the design in our friendly builder

Generate PDFs with our API or integrations