Converting HTML to PDF
HTML content can render differently across browsers, devices, and viewport sizes. Converting HTML to PDF gives you a fixed output format for sharing, archiving, and printing.
Use this workflow to:
- Preserve layout and styling in a stable document format
- Distribute web content for offline access
- Archive rendered pages for audit or compliance workflows
Use the Java SDK for conversion
Use the Java SDK to convert HTML to PDF directly in your app. Nutrient renders the HTML through Chrome, so the PDF preserves the page layout, fonts, images, and styling.
HTML-to-PDF conversion on Linux relies on Chrome for rendering. If you run this workflow in Docker on Linux, make sure the container includes Chrome and runs as a non-root user. For the packaged Docker setup, refer to the running Chrome-based conversions in Docker guide.
Preparing the project
Define a package and create a class for the conversion flow:
package io.nutrient.Sample;Import Nutrient Java SDK classes. Prefer explicit imports for the classes you use:
import io.nutrient.sdk.Document;import io.nutrient.sdk.exceptions.NutrientException;
public class HtmlToPDF {Create a main method and declare NutrientException:
public static void main(String[] args) throws NutrientException {Then add the SDK-specific conversion logic.
Proceeding with the conversion
The next step is to open the HTML file and export it as PDF.
This guide uses the Document class. Initialize it with a try-with-resources statement(opens in a new tab) so Java closes resources correctly:
try (Document document = Document.open("input.html")) {Use an absolute or relative path. This example reads from the working directory.
Export the rendered page as PDF. This example writes output.pdf to the working directory:
document.exportAsPdf("output.pdf"); } }}You now have a PDF file.
Error handling
The SDK throws NutrientException when conversion fails. Handle this exception in your app for custom logging, retries, or fallback logic.
Conclusion
You now have a complete HTML-to-PDF conversion flow in Java. Nutrient renders the HTML through Chrome and writes the result to output.pdf.
To run this example as-is, download the sample package.