Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

To convert a raw HTML string to PDF in Java, pass the string to a renderer and write the result to an output stream. iText pdfHTML provides a direct HtmlConverter.convertToPdf API; set a base URI when the HTML refers to relative images, stylesheets or other files. If your input can be kept to well-formed XHTML and a supported CSS subset, OpenHTMLtoPDF is a pure-Java open-source alternative. Neither choice should be assumed to render every modern webpage like a browser.

Choose a renderer before writing the conversion code

The important choice is not simply which library can write a PDF. It is whether the renderer supports the HTML and CSS you have, can resolve your assets and fonts, and meets your output and licensing requirements. For a controlled document template, a Java renderer can be practical. If the input is arbitrary, browser-oriented HTML, test representative pages before committing to a library.

Option Rendering scope established by its project information License or qualification Best fit to evaluate
iText pdfHTML Documented HTML5/CSS3-oriented support; the repository also describes SVG, searchable and accessible PDFs, and PDF/A workflows. Dual licensed under AGPL or commercial terms. Have legal counsel assess whether AGPL fits your distribution and use. When its documented feature set, accessibility or PDF/A capabilities are relevant and its licensing works for your application.
OpenHTMLtoPDF Pure Java, based on Apache PDFBox; renders a reasonable subset of well-formed XML/XHTML with CSS 2.1 and later standards, plus some HTML5. It can output PDF or images. LGPL. Its project documentation cautions that modern HTML5 should not be expected to render like it does in a browser. When you control the markup and can author for a constrained XHTML/CSS subset.
OpenPDF The repository includes an openpdf-html module; verify current compatibility and maintenance for your use case. Repository identifies LGPL/MPL licensing; review the applicable terms. As an alternative to assess, not as a presumed drop-in match for browser rendering.
Flying Saucer An older Java XHTML/CSS renderer oriented around XHTML 1.0 strict input; check current compatibility before adoption. Review current project terms for your specific release. Only after confirming its maintenance status and compatibility with your application.

Use these as evaluation candidates rather than a universal ranking. Check support for the exact CSS, SVG, tables, page breaks, fonts and accessibility output you need; whether the runtime can include a browser engine; how resource URLs are resolved; and the license obligations and support model.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Convert a Java String directly with iText pdfHTML

iText’s documented API accepts an HTML string and a destination. The following Java 11+ example creates a complete HTML document, writes it to a PDF file, and sets a base URI so relative resource paths have a predictable origin. Add the pdfHTML dependency and compatible iText modules using the current official iText integration instructions; no dependency version is pinned here because versions and compatibility change.

import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Path;

public class HtmlToPdf {
    public static void main(String[] args) throws IOException {
        String html = """
                <!doctype html>
                <html lang="en">
                <head>
                  <meta charset="UTF-8">
                  <title>Java HTML to PDF</title>
                  <style>
                    body { font-family: sans-serif; margin: 2rem; }
                    h1 { color: #17324d; }
                  </style>
                </head>
                <body>
                  <h1>Generated from a Java String</h1>
                  <p>This content is converted to PDF.</p>
                </body>
                </html>
                """;

        Path output = Path.of("output.pdf");
        String baseUri = Path.of(".").toAbsolutePath().toUri().toString();
        ConverterProperties properties = new ConverterProperties();
        properties.setBaseUri(baseUri);

        try (FileOutputStream stream = new FileOutputStream(output.toFile())) {
            HtmlConverter.convertToPdf(html, stream, properties);
        }
    }
}

Run the class with the pdfHTML libraries on its compile and runtime classpaths. On success, output.pdf is created in the process’s working directory. The example uses Java text blocks, available in Java 15 and later. On an older Java release, replace the text block with a regular escaped string or load the HTML from a file.

Why the base URI matters

A string has no inherent location. If it contains <img src="images/logo.png"> or a stylesheet link such as href="css/print.css", the renderer needs an origin to resolve those relative paths. In the example, the current directory becomes that origin. For production, set the URI to the directory or trusted resource location that actually contains the assets. Absolute URLs can avoid ambiguity, but remote resources must be reachable from the rendering environment.

Other supported destinations

iText documents conversions to destinations including an OutputStream, File, InputStream, PdfWriter and PdfDocument. Choose the overload that matches your application: a stream can write to an HTTP response or another destination, while a file is convenient for a local job. Keep the stream lifecycle explicit, as in the try-with-resources example.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use OpenHTMLtoPDF when you control the markup

OpenHTMLtoPDF is a strong open-source starting point when you can constrain the source to well-formed XHTML and CSS features it supports. It is a pure-Java renderer based on PDFBox, not a full browser. Its project documentation explicitly warns against sending modern HTML5 to it with browser-level expectations. That distinction matters if the input is copied from a live site or produced by a frontend framework.

For this route, normalize a fragment into a complete document, provide stable URLs or a resource resolver for images and stylesheets, and register the fonts your deployment needs. Follow the project’s current integration guide for the builder API and dependency versions rather than copying a version-sensitive snippet from an old example. Confirm that your actual document works with that release before using it in production.

Prepare the HTML and assets for predictable output

  1. Wrap fragments in a document. Supply a doctype, html, head and body, and set an explicit character encoding such as UTF-8. A fragment alone may leave document structure and encoding behavior to the renderer.
  2. Choose markup for the renderer. For OpenHTMLtoPDF, favor well-formed XHTML and supported CSS. For pdfHTML, still test the particular HTML and CSS you rely on; a documented HTML5/CSS3-oriented feature set is not a guarantee of identical output to every browser.
  3. Make asset resolution deterministic. Set a base URI or equivalent resolver for relative images and stylesheets. Check that paths are valid from the server process, not just from a developer’s workstation.
  4. Bundle and register fonts deliberately. Do not assume the production host has the same fonts as your laptop. Include permitted font files, configure the renderer to use them as appropriate for the selected library, and check font licensing.
  5. Design for page boundaries. Inspect long tables and content that spans pages. Use stable layouts and page-break behavior supported by the chosen renderer instead of relying on browser-specific CSS behavior.
  6. Test the real document set. Include representative images, links, tables, page breaks, non-Latin text and malformed input. Inspect the rendered PDF in the target deployment environment.
  7. Pin and review library releases. Keep versions deliberate and review release notes before upgrading; APIs, rendering support and licensing details can change.

Common conversion failures and practical fixes

Symptom Likely cause What to check
Images or stylesheets are missing Relative URLs have no usable origin, or the paths cannot be reached from the running service. Set the base URI or resolver; verify the asset path and the process’s access to it.
Characters display as boxes or incorrectly The expected font is unavailable, does not cover the characters, or encoding is not explicit. Declare UTF-8, bundle/register an appropriate permitted font, and test the target language and glyphs.
The page looks unlike its browser preview The renderer supports a different subset of HTML/CSS, or the markup depends on browser behavior. Check the renderer’s supported scope. Simplify or adapt the markup, then test the exact document rather than assuming full browser parity.
A table breaks awkwardly across pages The layout or page-break behavior is not stable in the chosen renderer. Test long tables and page boundaries; adjust the document structure and use layout rules supported by that renderer.
Output differs between local and server runs Fonts, assets, working directories or library versions differ. Make resource locations explicit, deploy the intended fonts, and pin the renderer dependencies.
Compilation fails on a converter method or builder The example and installed dependency versions do not match, or required modules are absent. Use the current official integration guide for the chosen release and align its required modules.
Legal review blocks a proposed library The application’s distribution model may not meet the selected license terms. Review the actual license obligations with counsel; for iText pdfHTML, assess AGPL versus a commercial license before shipping.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Performance, reliability and deployment considerations

Conversion cost depends on document complexity and resource availability; the available project information does not establish a universal speed or memory comparison between these libraries. Measure with representative documents in the runtime environment you will deploy. Include large images, long tables, remote or local assets, and the largest expected output in that test set.

For reliable jobs, avoid relying on a developer’s current directory or installed fonts. Use controlled asset locations, bound the size and complexity of untrusted HTML, and handle I/O and conversion failures at the application boundary. If HTML can come from users, treat external resource loading as a security and availability decision: accept only intended sources and do not let arbitrary references silently become dependencies. Capture representative output as a regression fixture when changing renderer versions or templates.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Accessibility, tagging and PDF/A are requirements to verify in the generated file, not merely checkboxes implied by a library’s feature description. Evaluate the specific output against the conformance needs of your application and the tools used by its recipients.

Or skip the browser setup

If your content is already available at a URL and a rendered screenshot or PDF is the goal, ScreenshotNeo offers a one-request capture API. It is not a replacement for converting an arbitrary Java HTML string with the libraries above: publish or serve the page at a URL first. For a screenshot of a page, the documented API call is:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo API documentation for setup and options. Cookie banners, newsletter popups and chat widgets are removed before the shot; bot checks, blank pages and failed loads are never billed. An MCP server lets AI agents take screenshots, and 1,000 screenshots a month are free with no card; paid plans start at $5 for 3,000. Sign up for ScreenshotNeo free.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.