Skip to content

Openpdf‐html‐example

Andreas Røsdal edited this page Jun 24, 2025 · 1 revision

openpdf-html: make PDF file from HTML

You can find a simple working example here: HelloWorldPdf.java

import org.openpdf.pdf.ITextRenderer;
import java.io.FileOutputStream;

public class HelloWorldPdf {
    public static void main(String[] args) throws Exception {
        String html = """
            <html>
              <head>
                <style>
                  body { font-family: sans-serif; }
                  h1 { color: navy; }
                </style>
              </head>
              <body>
                <h1>Hello, World!</h1>
                <p>This PDF was generated using openpdf-html.</p>
              </body>
            </html>
            """;

        try (FileOutputStream outputStream = new FileOutputStream("openpdf-html-hello.pdf")) {
            ITextRenderer renderer = new ITextRenderer();
            renderer.setDocumentFromString(html);
            renderer.layout();
            renderer.createPDF(outputStream);
        }

        System.out.println("PDF created: flying-saucer-hello.pdf");
    }
}
Clone this wiki locally