Convert HTML to PDF in Java

PDF files have many advantages over other formats, and sometimes you may need to convert HTML to PDF. This is particularly useful for creating high-quality, printer-friendly versions of web pages, generating reports, or sharing documents that are difficult to edit or modify.

The ability to easily and reliably convert HTML documents to other formats is one of the main features of Aspose.HTML for Java. In this article, you find information on how to convert HTML to PDF using convertHTML() methods of the Converter class, and how to apply PdfSaveOptions.

HTML to PDF by a single line of Java code

HTML to PDF conversion is a highly sought-after feature, and Aspose.HTML for Java offers an easy solution. Through static methods in the Converter class, you can convert an HTML document into a PDF file with just a single line of code!

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

In the example, we use the convertHTML(content, baseUri, options, outputPath) method of the Converter class that takes four parameters: string with HTML code to be converted, the base folder for the input HTML file, an instance of the PdfSaveOptions class, and the output file path where the converted file will be saved.

Convert HTML to PDF in Java

Let’s walk through the step-by-step instructions for a simple HTML to PDF conversion scenario:

  1. Load an HTML file using one of HTMLDocument() constructors of the HTMLDocument class. You can load HTML from a file, HTML code, stream, or URL (see the Creating an HTML Document article). In the example, we use HTMLDocument(address) constructor that initializes an HTML document from a file.
  2. Create a new PdfSaveOptions object. Use the empty PdfSaveOptions() constructor to convert with the default save options.
  3. Use the сonvertHTML(document, options, outputPath) method of the Converter class to save HTML as a PDF file.

Please review the following Java code snippet, which shows the HTML to PDF conversion process with step-by-step instructions:

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

Save Options – PdfSaveOptions Class

Aspose.HTML for Java allows converting HTML to PDF using default or custom save options. PdfSaveOptions allows you to customize the rendering process. You can specify the page size, margins, file permissions, media type, etc.

MetodDescription
setJpegQuality(value)Specifies the quality of JPEG compression for images. The default value is 95.
getCss()Gets a CssOptions object which is used for configuration of CSS properties processing.
setBackgroundColor(value)Sets the color that will fill the background of every page. By default, this property is Transparent.
setPageSetup(value)This method sets a page setup object and uses it for configuration output page-set.
setHorizontalResolution(value)Sets horizontal resolution for internal images, in pixels per inch. By default this property is 300 dpi.
setVerticalResolution(value)Sets vertical resolution for output images in pixels per inch. The default value is 300 dpi.
setEncryptionThis method gets or sets encryption details. If it is not set, then no encryption will be performed.

To learn more about PdfSaveOptions, please read the Fine-Tuning Converters article.

You can download the complete examples and data files from GitHub.

Convert HTML to PDF using PdfSaveOptions

With Aspose.HTML for Java, you can convert files programmatically with full control over a wide range of conversion parameters. Just follow a few steps:

  1. Load an HTML file using one of the HTMLDocument() constructors of the HTMLDocument class.
  2. Create a new PdfSaveOptions object and specify the required properties. The PdfSaveOptions() constructor initializes an instance of the PdfSaveOptions class that is passed to convertHTML() method.
  3. Use the сonvertHTML(document, options, outputPath) method of the Converter class to save HTML as a PDF file.

The following Java example shows how to use PdfSaveOptions and create a PDF file with custom page-size, margins, resolutions, background color, and compression specifying:

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

In the example above, several PDF save options were used:

One more Java example. Here we create HTML document from scratch – prepare HTML code and save it to a file. Then we apply PdfSaveOptions to convert HTML to PDF:

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

Conclusion

Converting HTML to PDF is a useful feature for creating high-quality, shareable, and print-friendly documents. Aspose.HTML for Java provides a robust solution with the Converter class, allowing you to easily convert HTML to PDF using flexible methods such as convertHTML() and customizable PdfSaveOptions.

The PdfSaveOptions class allows developers to customize the output by specifying page sizes, margins, resolutions, background colors, compression options, encryption, etc., ensuring accurate and professional results. If you create reports and save web content as PDF documents, Aspose.HTML for Java simplifies the process with minimal code.

Aspose.HTML offers a free online HTML to PDF Converter that converts HTML to PDF with high quality, easy and fast. Just upload, convert your files and get the result in a few seconds!

Text “HTML to PDF Converter”

Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.