This article shows HTML to PDF conversion from a file or web page using Java.

HTML to PDF Java

The online HTML to PDF converters allow you to convert single or multiple HTML pages to PDF documents. However, if you need to perform this conversion programmatically or require batch conversion of HTML files to PDF, you will need a library or API. Below are the key topics covered:

HTML to PDF Java Converter API - Free Download

Aspose.PDF for Java is a powerful Java class library for working with PDF documents. In addition to PDF manipulation features, the API provides high‑quality HTML to PDF conversion. You can download the API’s JAR file or install it via Maven.

Repository:

<repository>
    <id>AsposeJavaAPI</id>
    <name>Aspose Java API</name>
    <url>https://repository.aspose.com/repo/</url>
</repository>

Dependency:

<dependency>
    <groupId>com.aspose</groupId>
    <artifactId>aspose-pdf</artifactId>
    <version>19.12</version>
    <classifier>jdk17</classifier>
</dependency>

How to Convert HTML to PDF

Follow these steps to convert HTML content to PDF using Aspose.PDF API:

  • Download Aspose.PDF for Java
  • Integrate the API into your application
  • Load the HTML content from a file or URL
  • Create a PDF from the loaded HTML

HTML to PDF Java Conversion

Convert an HTML file to PDF with Java:

  • Create an instance of the HtmlLoadOptions class.
  • Create a Document object, initializing it with the HTML file path and the HtmlLoadOptions instance.
  • Call Document.save(String) with the desired PDF file name.

The sample below demonstrates converting an HTML document to PDF.

Input HTML File

Java HTML to PDF

Converted PDF Document

Java HTML to PDF Library

Convert HTML to Password-Protected PDF in Java

Aspose.PDF also supports converting HTML files to encrypted PDFs. Specify user password, owner password, permissions, and cryptographic algorithm in the Document.encrypt() method.

Output

Convert HTML to PDF

Convert HTML to PDF using URL in Java

Convert a live web page to PDF:

  • Create and initialize a URL object.
  • Retrieve the page into an InputStream.
  • Create a Document using the InputStream and HtmlLoadOptions.
  • Save the PDF with Document.save().

HTML to a Single Page PDF

To render the entire HTML content on a single PDF page, set HtmlLoadOptions.setRenderToSinglePage(true) as shown below.

Get API’s License for Free

Obtain a temporary license to evaluate Aspose.PDF for Java for free for one month.

Conclusion

This article demonstrated how to convert HTML from a file or URL to PDF using Java. Code samples cover standard conversion, single‑page PDFs, and password‑protected PDFs. Explore more features in the Aspose.PDF for Java documentation.

Info: Aspose also provides a Java PowerPoint API that lets you create PDFs from presentations and a free online PowerPoint to PDF Converter that demonstrates the process.