Convert HTML to PDF in Java

To convert HTML to PDF in Java, load the source with HTMLDocument, create PdfSaveOptions, and call Converter.convertHTML(). You can convert an HTML file or pass an HTML string and base URI directly to a supported overload.

Converting HTML to PDF creates a fixed-layout document suitable for printing, reports, and distribution. Aspose.HTML for Java provides convertHTML() overloads for different HTML inputs and PdfSaveOptions for configuring PDF output.

Convert HTML to PDF in One Line of Java Code

The following example passes an HTML string, base URI, PdfSaveOptions, and output path directly to Converter.convertHTML():

1// Convert HTML to PDF in one line using Java
2
3// Invoke the convertHTML() method to convert the HTML to PDF
4Converter.convertHTML("<h1>Convert HTML to PDF!</h1>", ".", new PdfSaveOptions(), "convert-with-single-line.pdf");

The base URI ("." in the example) is used to resolve relative resources in the HTML string. The PDF is saved as convert-with-single-line.pdf.

Convert an HTML File to PDF

Follow these steps to convert an existing HTML file:

  1. Create the source HTML file and load it with HTMLDocument.
  2. Create PdfSaveOptions. The parameterless constructor uses the default PDF save settings.
  3. Call Converter.convertHTML(document, options, outputPath) to save the PDF.
 1// Convert HTML to PDF using Java
 2
 3// Prepare HTML code and save it to a file
 4String code = "<span>Hello, World!!</span>";
 5try (java.io.FileWriter fileWriter = new java.io.FileWriter("link-to-incoming-document.html")) {
 6    fileWriter.write(code);
 7}
 8
 9// Initialize an HTML document from the file
10HTMLDocument document = new HTMLDocument("link-to-incoming-document.html");
11
12// Initialize PdfSaveOptions
13PdfSaveOptions options = new PdfSaveOptions();
14
15// Convert HTML to PDF
16Converter.convertHTML(document, options, "document-output.pdf");

Customize PDF Output with PdfSaveOptions

Use PdfSaveOptions to configure page layout, resolution, background color, JPEG image quality, CSS processing, and encryption.

MethodUse it to
setJpegQuality(value)Set JPEG compression quality when JPEG compression is used. The default is 95.
setBackgroundColor(value)Set the color that fills each output page. The default is transparent.
getPageSetup()Access the page setup used to configure output page size and margins.
setHorizontalResolution(value)Set horizontal resolution for internal images. The default is 300 dpi.
setVerticalResolution(value)Set vertical resolution for internal images. The default is 300 dpi.
getCss()Access CSS processing options.
setEncryption(value)Set PDF encryption details. No encryption is applied when this option is not set.

For additional settings, see Fine-Tuning Converters. Download complete examples and data files from GitHub.

The following example demonstrates a customized HTML-to-PDF conversion:

  1. Load the source HTML file into an HTMLDocument.
  2. Create PdfSaveOptions and set 200 dpi resolution, an Alice Blue background, JPEG quality of 100, and a 500 × 300 pixel page with custom margins.
  3. Call Converter.convertHTML(document, options, outputPath) to convert HTML to PDF.

In this example, the input is drawing.html, and the result is saved as drawing-options.pdf.

 1// Convert HTML to PDF in Java with custom page settings
 2
 3// Initialize an HTML document from a file
 4HTMLDocument document = new HTMLDocument("drawing.html");
 5
 6// Initialize PdfSaveOptions. Set up the page-size 500x300 pixels, margins,
 7// resolutions and change the background color to AliceBlue
 8PdfSaveOptions options = new PdfSaveOptions();
 9options.setHorizontalResolution(new Resolution(200, UnitType.AUTO));
10options.setVerticalResolution(new Resolution(200, UnitType.AUTO));
11options.setBackgroundColor(Color.getAliceBlue());
12options.setJpegQuality(100);
13options.getPageSetup().setAnyPage(new Page(new Size(500, 300), new Margin(20, 10, 10, 10)));
14
15// Convert HTML to PDF
16Converter.convertHTML(document, options, "drawing-options.pdf");

The next example creates save-options.html, loads it as an HTMLDocument, and converts it to save-options-output.pdf. It sets an Antique White background and configures page dimensions in inches with custom margins.

 1// Convert HTML to PDF with custom settings using Java
 2
 3// Prepare HTML code and save it to a file
 4String code = "<h1>  PdfSaveOptions Class</h1> " +
 5        "<p>Using PdfSaveOptions Class, you can programmatically " +
 6        "apply a wide range of conversion parameters " +
 7        "such as BackgroundColor, HorizontalResolution, VerticalResolution, PageSetup, etc.</p>";
 8
 9FileHelper.writeAllText("save-options.html", code);
10
11// Initialize an HTML Document from the HTML file
12HTMLDocument document = new HTMLDocument("save-options.html");
13
14// Set up the page-size, margins and change the background color to AntiqueWhite
15PdfSaveOptions options = new PdfSaveOptions();
16options.setBackgroundColor(Color.getAntiqueWhite());
17options.getPageSetup().setAnyPage(
18        new Page(
19                new Size(Length.fromInches(4.9f), Length.fromInches(3.5f)),
20                new Margin(30, 20, 10, 10)
21        )
22);
23
24// Convert HTML to PDF
25Converter.convertHTML(document, options, "save-options-output.pdf");

Related HTML Conversion Guides

Other Platforms

FAQ

Can I convert HTML to PDF for free?

Yes. Use the free online HTML to PDF Converter for a quick manual conversion. Aspose.HTML for Java is a commercial API for programmatic conversion and can be evaluated before licensing; see Licensing.

Can I convert an HTML string directly to PDF?

Yes. Call a Converter.convertHTML() overload that accepts the HTML string, a base URI, PdfSaveOptions, and an output path. The base URI is required to resolve any relative URLs in the supplied HTML.

How are CSS, images, and fonts resolved during HTML-to-PDF conversion?

Relative CSS and image URLs are resolved against the HTML document URL or the base URI supplied with an HTML string. Use a valid base URI and make sure the referenced resources are accessible during conversion. Fonts must be available in the rendering environment; to use custom fonts, configure a font folder with FontsSettings.setFontsLookupFolder(). See Create an HTML Document and Environment Configuration for details.

Try Online HTML to PDF Conversion

Use the free online HTML to PDF Converter for quick manual conversion without writing Java code.

Free Online HTML to PDF Converter