DEV Community

E-iceblue Product Family
E-iceblue Product Family

Posted on

Convert HTML to PDF and PDF to HTML in Java

Occasionally, you may want to convert a beautiful HTML page to PDF to store it on your device or share it with your friends, however, sometimes if you want to view the content of a PDF file on various platforms without installing a PDF document viewer, you probably want to convert it to HTML. In this article, I’m going to introduce how to convert HTML to PDF and PDF to HTML programmatically in Java using Spire.PDF for Java API.

Get JAR

You can download the API’s JAR file from this link or install using the following Maven configurations.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId> e-iceblue </groupId>
        <artifactId>spire.pdf</artifactId>
        <version>3.10.5</version>
    </dependency>
</dependencies>
Enter fullscreen mode Exit fullscreen mode

Convert HTML to PDF

Spire.PDF for Java API supports converting HTML to PDF with QT Plugin.
Before using the following code, you need to download the corresponding plugin package according to the type and version of your Operating System and then unzip the package.

Download Plugin:
windows-x86.zip
windows-x64.zip
macosx_x64.zip
linux_x64.zip

The following example shows how to convert a HTML page to PDF using Spire.PDF for Java.

import com.spire.pdf.graphics.PdfMargins;
import com.spire.pdf.htmlconverter.qt.HtmlConverter;
import com.spire.pdf.htmlconverter.qt.Size;

public class ConvertHtmlToPdf {
    public static void main(String[] args){
        String url = "https://www.e-iceblue.com/";
        String fileName = "Result.pdf";
        //Specify the plugin path
        String pluginPath = "data/plugins";
        HtmlConverter.setPluginPath(pluginPath);
        //Convert HTML to PDF with specified page size
        HtmlConverter.convert(url, fileName, true, 1000000, new Size(600f, 900f), new PdfMargins(0));
    }
}
Enter fullscreen mode Exit fullscreen mode

Convert PDF to HTML

Convert PDF to HTML with Spire.PDF for Java is a very simple task - you just need to add 3 lines of code to your main class as shown in the following code example.

import com.spire.pdf.FileFormat;
import com.spire.pdf.PdfDocument;

public class ConvertPdfToHtml {
    public static void main(String[] args){
        //Load the PDF file
        PdfDocument pdf = new PdfDocument();
        pdf.loadFromFile("New Zealand.pdf");
        //Save to HTML format
        pdf.saveToFile("ToHTML.html", FileFormat.HTML);
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)