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.
1. From the official website of E-iceblue Free Spire.doc for Java Download the free version.
2. Start the IDE, create a new project, and then add the appropriate Spire.doc.jar for the installed files to your references.
SaveHTML 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);
}
}
Recommended Posts