Convert HTML to PDF Using Java

In this article, you find information on how to convert an HTML document into a Portable Document Format (PDF) file format using Aspose.HTML for Java library. 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.

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 and ICreateStreamProvider parameters.

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 сonvertHTML() method to convert HTML to PDF
2    com.aspose.html.converters.Converter.convertHTML("<h1>Convert HTML to PDF!</h1>", ".", new PdfSaveOptions(), Path.combine(getOutputDir(), "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 a path to a source HTML file
 2    String documentPath = Path.combine(getDataDir(), "spring.html");
 3
 4    // Prepare a path for converted file saving 
 5    String outputPath = Path.combine(getOutputDir(), "spring-output.pdf");
 6
 7    // Initialize an HTML document from the file
 8    HTMLDocument document = new HTMLDocument(documentPath);
 9    try {        }
10    finally { if (document != null) document.dispose(); }
11
12    // Initialize PdfSaveOptions object
13    PdfSaveOptions options = new PdfSaveOptions();
14
15    // Convert HTML to PDF
16    com.aspose.html.converters.Converter.convertHTML(document, options, outputPath);

Save Options

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, CSS 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 in Java using PdfSaveOptions

With Aspose.HTML for Java, you can convert files programmatically with full control over a wide range of conversion parameters. To convert HTML to PDF with PdfSaveOptions specifying, you should 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.
  3. Use the сonvertHTML() 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    // Prepare a path to a source HTML file
 2    String documentPath = Path.combine(getDataDir(), "drawing.html");
 3
 4    // Prepare a path for converted file saving 
 5    String outputPath = Path.combine(getOutputDir(), "drawing-options.pdf");
 6
 7    // Initialize an HTML document from the file
 8    HTMLDocument   document = new HTMLDocument(documentPath);
 9    try {        }
10    finally { if (document != null) document.dispose(); }
11
12    // Initialize PdfSaveOptions. Set up the page-size 500x300 pixels, margins, resolutions and change the background color to AliceBlue 
13    PdfSaveOptions options = new PdfSaveOptions();
14    options.setHorizontalResolution(new Resolution(200, UnitType.AUTO));
15    options.setVerticalResolution(new Resolution(200, UnitType.AUTO));;
16    com.aspose.html.drawing.Color.getAliceBlue().CloneTo(options.getBackgroundColor());
17    options.setJpegQuality(100);
18    options.getPageSetup().setAnyPage(new Page(new com.aspose.html.drawing.Size(500, 300), new Margin(20, 10, 10, 10)));
19
20    // Convert HTML to PDF
21    com.aspose.html.converters.Converter.convertHTML(document, options, outputPath);    

The PdfSaveOptions() constructor initializes an instance of the PdfSaveOptions class that is passed to convertHTML() method. The method takes the document, options, output file path outputPath and performs the conversion operation.

The PdfSaveOptions class provides methods that give you full control over a wide range of parameters and improve the process of converting HTML to PDF format. In the example above, several 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    String documentPath = Path.combine(getOutputDir(), "save-options.html");
 2    String savePath = Path.combine(getOutputDir(), "save-options-output.pdf");
 3
 4    // Prepare HTML code and save it to a file
 5    String code = StringExtensions.concat("<h1>PdfSaveOptions Class</h1>\r\n", 
 6              "<p>Using PdfSaveOptions Class, you can programmatically apply a wide range of conversion parameters such as BackgroundColor, Resolutions, PageSetup, etc.</p>\r\n");
 7
 8    com.aspose.html.internal.ms.System.IO.File.writeAllText(documentPath, code);
 9
10    // Initialize an HTML Document from the html file
11    HTMLDocument   document = new HTMLDocument(documentPath);
12    try {        }
13    finally { if (document != null) document.dispose(); }
14        
15    // Set up the page-size, margins and change the background color to AntiqueWhite
16    PdfSaveOptions  options = new PdfSaveOptions();
17    com.aspose.html.drawing.Color.getAntiqueWhite().CloneTo(options.getBackgroundColor());
18    options.getPageSetup().setAnyPage(new Page(new com.aspose.html.drawing.Size(com.aspose.html.drawing.Length.fromInches(4.9f), com.aspose.html.drawing.Length.fromInches(3.5f))));
19
20    // Convert HTML to PDF
21    com.aspose.html.converters.Converter.convertHTML(document, options, savePath);   

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 “Banner HTML to PDF Converter”

Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.