En

KNOWLEDGEBASE

Generate PDF from HTML using Java [Step-by-step]

This article will show you how to generate PDFs from HTML using Java. You can easily manipulate and render HTML documents including CSS styles.

Aspose.HTML for Java enables your applications to perform a broad of HTML manipulation tasks and supports HTML5, CSS3, SVG, and HTML Canvas features. With our API you can load web pages, analyze, edit the content, and save and convert pages. Popular formats that you can manipulate: XHTML, MHTML, SVG, MD, PDF, XPS, EPUB, PNG, TIFF, JPEG, BMP, and others.

PDF from HTML in Java

Rich set of features

Aspose.HTML for Java offers you a lot of features in many different areas:

• Document object model - allows you to edit, create and remove nodes, and is built according to the official HTML documentation.
• High-performance converters. For more info about supported file formats visit Features List or Converting articles.
• Processing CSS, JavaScript, and other built-in formats.

Generate PDF from HTML with a single line of Java code

You can easily generate PDF from HTML in your Java application with literally a single line of code using the static methods of the Converter class.

// Invoke the ConvertHTML method to convert the HTML to PDF.
com.aspose.html.converters.Converter.convertHTML(
        "<span>Hello World!!</span>",
        ".",
        new com.aspose.html.saving.PdfSaveOptions(),
        "output.pdf"
);

Generate PDF from HTML line by line using Java

Below are the steps to generate PDF from HTML line by line:

  1. Using HtmlDocument class first load the HTML file.
  2. After that create an instance of PdfSaveOptions.
  3. With ConvertHTML() method of Converter class save HTML as a PDF file. You will need to pass the HTMLDocument, PdfSaveOptions, and output file path to the ConvertHTML() method to generate PDF from HTML.
// Prepare an HTML code and save it to the file.
String code = "<span>Hello World!!</span>";
try (java.io.FileWriter fileWriter = new java.io.FileWriter("document.html")) {
    fileWriter.write(code);
}

// Initialize an HTML document from the file
com.aspose.html.HTMLDocument document = new com.aspose.html.HTMLDocument("document.html");
try {
    // Initialize PdfSaveOptions
    com.aspose.html.saving.PdfSaveOptions options = new com.aspose.html.saving.PdfSaveOptions();

    // Convert HTML to PDF
    com.aspose.html.converters.Converter.convertHTML(
            document,
            options,
            "output.pdf"
    );
} finally {
    if (document != null) {
        document.dispose();
    }
}

Customize the rendering process with the Save option

You can customize the rendering process with the PdfSaveOptions, and specify the page size, file permissions, margins, CSS media type, and many more. In the example shown below you can see how to use PdfSaveOptions and create a PDF file with a custom page size and background color:

// Prepare an HTML code and save it to the file
String code = "<span>Hello</span> <span>World!!</span>";
try (java.io.FileWriter fileWriter = new java.io.FileWriter("document.html")) {
    fileWriter.write(code);
}

// Set A5 as a page-size and change the background color to green
com.aspose.html.saving.PdfSaveOptions options = new com.aspose.html.saving.PdfSaveOptions();
com.aspose.html.rendering.PageSetup pageSetup = new com.aspose.html.rendering.PageSetup();
com.aspose.html.drawing.Page anyPage = new com.aspose.html.drawing.Page();
anyPage.setSize(
        new com.aspose.html.drawing.Size(
                com.aspose.html.drawing.Length.fromInches(8.3f),
                com.aspose.html.drawing.Length.fromInches(5.8f)
        )
);
pageSetup.setAnyPage(anyPage);
options.setPageSetup(pageSetup);

options.setBackgroundColor(com.aspose.html.drawing.Color.getGreen());

// Convert HTML document to PDF
com.aspose.html.converters.Converter.convertHTML(
        "document.html",
        options,
        "output.pdf"
);

In the Fine-Tuning Converters article, you can find more about PdfSaveOptions.

Output stream provider

You can implement MemoryStreamProvider interface if you want to save files in remote storage, like the cloud or database.
MemoryStreamProvider interface is designed as a callback object to create a stream and release the early created stream after rendering the page or document.

We will show you an example of using MemoryStreamProvider below:

package com.aspose.html.examples.java;

// For complete examples and data files, please go to https://github.com/aspose-html/Aspose.HTML-for-Java
public class MemoryStreamProvider implements java.io.Closeable {
    // List of InputStream objects created during the document rendering
    public java.util.List<java.io.InputStream> lStream = new java.util.ArrayList<>();

    @Override
    public void close() throws java.io.IOException {
        for (java.io.InputStream stream : lStream) {
            stream.close();
        }
    }
}
// Create an instance of MemoryStreamProvider
try (MemoryStreamProvider streamProvider = new MemoryStreamProvider()) {
    // Initialize an HTML document
    com.aspose.html.HTMLDocument document = new com.aspose.html.HTMLDocument("<span>Hello World!!</span>", ".");
    try {
        // Convert HTML to PDF by using the MemoryStreamProvider
        com.aspose.html.converters.Converter.convertHTML(
                document,
                new com.aspose.html.saving.PdfSaveOptions(),
                streamProvider.lStream
        );

        // Get access to the memory stream that contains the result data
        java.io.InputStream inputStream = streamProvider.lStream.stream().findFirst().get();

        // Flush the result data to the output file
        try (java.io.FileOutputStream fileOutputStream = new java.io.FileOutputStream("output.pdf")) {
            byte[] buffer = new byte[inputStream.available()];
            inputStream.read(buffer);
            fileOutputStream.write(buffer);
        }
    } finally {
        if (document != null) {
            document.dispose();
        }
    }
}

Aspose provides technical support for all its products, from knowledge base articles, documentation, blog, code samples, and demos, to Free Support as well as highly available Paid Support.
If you need experts who will work together with you and help you implement the Aspose.HTML for Java according to your needs, the best solution is our Paid Consulting.