Convert HTML to PDF in Java

2020-09-29 08:40:24 Written by  support iceblue
Rate this item
(0 votes)

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

Additional Info

  • tutorial_title:
Last modified on Wednesday, 01 September 2021 09:10