Free tools Windows power users keep installed

One-click scans. No signup required.

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

To convert a raw HTML string to PDF in Java, pass the string to a renderer such as iText pdfHTML’s HtmlConverter.convertToPdf method. Give the renderer a base URI when the HTML refers to relative images, stylesheets, or other files. For a constrained, well-formed XHTML/CSS document, OpenHTMLtoPDF is an open-source alternative; it is not a full browser engine.

Choose a renderer for the HTML you have

The key decision is how closely your input depends on browser behavior. A short, controlled document with well-formed markup and supported CSS can work with a Java renderer. A page built around modern browser features needs careful compatibility testing; do not assume a PDF library will render it exactly as Chrome or Firefox would.

Library Good fit Important qualification
iText pdfHTML Direct conversion from a Java String, with documented HTML5/CSS3-oriented support and options for PDF/A and accessible PDFs. Dual-licensed under AGPL or a commercial license. Review the applicable terms for your distribution model.
OpenHTMLtoPDF A pure-Java, open-source option when you can author well-formed XHTML and stay within its supported CSS and HTML subset. It is not a browser-level renderer. The project describes support for a reasonable subset of XHTML and some HTML5, using CSS 2.1 and later standards.
OpenPDF An open-source Java PDF library with an openpdf-html module. Check current compatibility, maintenance, and LGPL/MPL licensing for your specific use.
Flying Saucer An older Java XHTML/CSS renderer that can produce PDFs. It is oriented around XHTML 1.0 strict input; review current compatibility and maintenance before adopting it.

For OpenHTMLtoPDF, the project itself cautions against expecting a great result from modern HTML5 input. For iText, assess both the HTML/CSS you need and whether AGPL terms or a commercial license fit your application. These projects’ feature descriptions and license terms are their own; verify the current integration guidance and terms before shipping.

Convert a raw HTML string with iText pdfHTML

The direct path is to call HtmlConverter.convertToPdf with your HTML string and an output stream. The following example writes a PDF file and sets a base URI so relative asset paths can resolve.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.html2pdf.ConverterProperties;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class HtmlToPdf {
    public static void main(String[] args) throws IOException {
        String html = "<!doctype html>"
                + "<html><head>"
                + "<meta charset="UTF-8">"
                + "<style>body { font-family: sans-serif; }</style>"
                + "</head><body>"
                + "<h1>Hello from HTML</h1>"
                + "<p>This content is converted to PDF.</p>"
                + "</body></html>";

        Path output = Paths.get("output.pdf");
        Path assets = Paths.get("html-assets").toAbsolutePath();
        ConverterProperties properties = new ConverterProperties();
        properties.setBaseUri(assets.toUri().toString());

        try (OutputStream out = Files.newOutputStream(output)) {
            HtmlConverter.convertToPdf(html, out, properties);
        }
    }
}

Compile this with the iText pdfHTML dependency available to your project. The code uses the documented HtmlConverter and ConverterProperties APIs; use the current iText integration documentation for dependency coordinates and version-specific setup. The base URI points to an html-assets directory beside the process’s working directory. If an HTML element refers to images/logo.png, place that file under html-assets/images/logo.png, or set the base URI to the directory that actually contains the referenced resources.

Convert to another destination

iText’s conversion API also accepts destinations including a File, InputStream, OutputStream, PdfWriter, and PdfDocument. Writing to an output stream is useful when the PDF should go to a network response or another destination rather than a local file; manage the stream’s lifecycle in the calling application.

Handle fragments and encoding deliberately

If your input is only a fragment such as <h1>Invoice</h1>, wrap it in a complete HTML document before conversion. Include an explicit character encoding, normally UTF-8, and put document-level styles in the document or in a stylesheet that the renderer can resolve. This makes the rendering environment less dependent on implicit defaults.

Use OpenHTMLtoPDF for constrained XHTML

OpenHTMLtoPDF is a pure-Java renderer based on Apache PDFBox and is licensed under LGPL. It can be a strong starting point when you control the markup and can keep it within a well-formed XHTML/CSS subset. A typical integration builds a renderer with HTML content, a base URI, and an output stream:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import com.openhtmltopdf.pdfboxout.PdfRendererBuilder;

import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class XhtmlToPdf {
    public static void main(String[] args) throws Exception {
        String xhtml = "<html xmlns="http://www.w3.org/1999/xhtml">"
                + "<head><meta charset="UTF-8" />"
                + "<style>body { font-family: sans-serif; }</style>"
                + "</head><body>"
                + "<h1>Hello from XHTML</h1>"
                + "<p>This content is converted to PDF.</p>"
                + "</body></html>";

        Path output = Paths.get("output.pdf");
        Path assets = Paths.get("html-assets").toAbsolutePath();
        try (OutputStream out = Files.newOutputStream(output)) {
            new PdfRendererBuilder()
                    .withHtmlContent(xhtml, assets.toUri().toString())
                    .toStream(out)
                    .run();
        }
    }
}

Use the project’s current integration guide to select dependency versions and confirm the builder API for the version you pin. OpenHTMLtoPDF supports font fallback and advertises SVG, PDF/A, and accessible-PDF-related capabilities, but those claims do not mean arbitrary web pages or every CSS feature will render as desired. Validate the exact output you need in your target environment.

Make assets, fonts, and page layout deterministic

  • Relative resources: A path like images/chart.png has no reliable meaning without a base URI or equivalent resource resolver. For iText, set it with ConverterProperties.setBaseUri. Keep asset locations stable in development and deployment.
  • Fonts: Bundle and register permitted font files where the renderer supports it rather than relying on fonts installed on a particular server. Check font licensing, and test accented text and non-Latin scripts that matter to your users.
  • Page breaks and tables: Long tables, images, and page-break rules can expose differences between browser layout and PDF rendering. OpenHTMLtoPDF recommends stable table layouts around page breaks. Test representative long documents instead of relying on a one-page sample.
  • SVG and accessibility: If vector artwork, tagged output, accessibility, or PDF/A conformance is a requirement, evaluate the library’s support against a real sample and inspect the generated file. A feature description is not a substitute for validating your document.
  • Malformed input: Normalize or repair fragments before conversion. OpenHTMLtoPDF is intended for well-formed XML/XHTML input; malformed HTML and browser-specific markup can produce missing or unexpected content.

Or skip the browser setup

If your source is already a publicly reachable web page and you want a PDF capture, ScreenshotNeo can capture a URL without you setting up a browser in your application. It is a different workflow from converting an arbitrary in-memory HTML string: this request targets a URL. The example below is the documented one-call screenshot form; consult the ScreenshotNeo API documentation for PDF output and capture options.

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

ScreenshotNeo removes cookie or consent banners, newsletter popups, and chat widgets before capture, with each cleanup step configurable. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing; response headers identify the page verdict and billing status. Its MCP server offers take_screenshot, get_page_info, and capture_pdf for AI agents and MCP clients. The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000. See ScreenshotNeo, or sign up free for 1,000 screenshots a month with no card.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshoot common conversion failures

Symptom Likely cause What to check
Images or stylesheets are missing Relative paths are being resolved from an unset or incorrect base location. Set the base URI to the assets’ actual parent directory and confirm the files are accessible to the Java process.
Some CSS looks different from a browser The renderer supports a subset of web layout and CSS rather than all browser behavior. Reduce the page to supported markup and styles, check the selected renderer’s current documentation, and test the exact page layout.
Characters appear as boxes or are missing The chosen font may not contain the glyphs or may not be available in the deployment environment. Bundle/register a suitable licensed font and test the relevant scripts in the deployed runtime.
Content is missing around a page break A table, image, or block may not paginate as expected by the renderer. Test long-content cases; for OpenHTMLtoPDF, use stable table layouts around page breaks.
Modern page content is absent The input may rely on browser-level HTML5, CSS, or execution behavior that the Java renderer does not provide. Constrain or simplify the source for the renderer, or reassess whether a Java HTML renderer is appropriate.
PDF output differs after deployment Fonts, resource paths, dependency versions, or runtime assumptions differ from the development environment. Bundle fonts/assets, pin library versions, and render representative pages in the same environment used in production.

Test before you ship

  1. Wrap each raw fragment in a complete document with explicit encoding.
  2. Choose iText pdfHTML when its documented rendering capabilities and license terms fit; choose OpenHTMLtoPDF when the XHTML/CSS constraints are acceptable.
  3. Set a base URI or resource resolver and make required assets available to the process.
  4. Bundle suitable fonts and verify their licenses.
  5. Render samples containing long tables, page breaks, images, links, non-Latin text, and malformed input.
  6. Inspect the PDF in the target deployment environment, pin library versions, and review release notes before shipping.

FAQ

Can ScreenshotNeo convert a Java HTML string?

No. Its documented input is a URL, so it is an option for capturing a reachable page, not a drop-in converter for an arbitrary raw HTML string held in Java.

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

Frequently Asked Questions

Can ScreenshotNeo convert a Java HTML string?

No. Its documented input is a URL, so it is an option for capturing a reachable page, not a drop-in converter for an arbitrary raw HTML string held in Java.

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.