Convert HTML to PDF in Java

This article will demonstrate how to use Spire.Doc for Java to convert HTML string and HTML file to PDF in Java applications.

HTML String to PDF

import com.spire.doc.*;
import java.io.*;

public class htmlStringToWord {

    public static void main(String[] args) throws Exception {

        String inputHtml = "InputHtml.txt";
        //Create a new document
        Document document = new Document();
        //Add a section
        Section sec = document.addSection();

        String htmlText = readTextFromFile(inputHtml);
        //add a paragraph and append html string.
        sec.addParagraph().appendHTML(htmlText);

        //Save to PDF
        document.saveToFile("HTMLstringToPDF.pdf", FileFormat.PDF);
    }
    public static String readTextFromFile(String fileName) throws IOException{
        StringBuffer sb = new StringBuffer();
        BufferedReader br = new BufferedReader(new FileReader(fileName));
        String content = null;
        while ((content = br.readLine()) != null) {
            sb.append(content);
        }
        return sb.toString();
    }
}

Java Convert HTML to PDF

Convert HTML file to PDF

import com.spire.doc.*;
import com.spire.doc.documents.XHTMLValidationType;

public class htmlFileToWord {

    public static void main(String[] args) throws Exception {
        // Load the sample HTML file
        Document document = new Document();
        document.loadFromFile("InputHtmlFile.html", FileFormat.Html, XHTMLValidationType.None);

        //Save to file
        document.saveToFile("Result.pdf",FileFormat.PDF);
    }
}

Effective screenshot:

Java Convert HTML to PDF