Save Java HTML as PDF

There are various ways to save HTML as PDF, but when I tried searching on the net, it would be complicated.

Now, in the main text, I will show you how to save the HTML format of HTML String and HTML file as PDF through Spire.Doc for Java.

Preparation

1. From the official website of E-iceblue Free Spire.doc for Java Download the free version.

f:id:lendoris:20201216121839p:plain

2. Start the IDE, create a new project, and then add the appropriate Spire.doc.jar for the installed files to your references.

f:id:lendoris:20201216121952p:plain

Save

HTML String PDF

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

public class htmlStringToWord {

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

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

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

    //Save as 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();
}

}


 <h4> Save HTML file as PDF </h4>
```java
import com.spire.doc.*;
import com.spire.doc.documents.XHTMLValidationType;

public class htmlFileToWord {

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

        //you save.
        document.saveToFile("Result.pdf",FileFormat.PDF);
    }
}

 

f:id:lendoris:20201216123643p:plain

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Recommended Posts

Save Java HTML as PDF
Save Java PDF in Excel
[Java] Convert PDF version
Java compressed PDF document
[Java] PDF viewing settings
Java adds table to PDF
Java turns Excel into PDF
JavaScript as seen from Java
HTML parsing with JAVA (scraping)
I created a PDF in Java.
Java to extract PDF text content
[Java] December 28, 2020 will be formatted as December 28, 2021?
Avoid Java Calendar as much as possible
Add, modify, delete JAVA PDF bookmarks
Output PDF and TIFF with Java 8
Add, replace, delete Java PDF images
Add watermark to Java to PDF document
Html5 development with Java using TeaVM
Java draws shapes in PDF documents
Java adds form fields to PDF
[Java] Resource interpreted as Stylesheet but transferred with MIME type text / html