本文将介绍如何使用Spire.Doc for Java将HTML String和HTML file两种HTML样式的文档保存为PDF格式。
HTML String另存为PDF格式
import com.spire.doc.*;
import java.io.*;
public class htmlStringToWord {
public static void main(String[] args) throws Exception {
String inputHtml = "InputHtml.txt";
//新建Document对象
Document document = new Document();
//添加section
Section sec = document.addSection();
String htmlText = readTextFromFile(inputHtml);
//添加段落并写入HTML文本
sec.addParagraph().appendHTML(htmlText);
//文档另存为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();
}
}
HTML file另存为PDF格式
import com.spire.doc.*;
import com.spire.doc.documents.XHTMLValidationType;
public class htmlFileToWord {
public static void main(String[] args) throws Exception {
//加载HTML文档
Document document = new Document();
document.loadFromFile("InputHtmlFile.html", FileFormat.Html, XHTMLValidationType.None);
//文档另存为PDF
document.saveToFile("Result.pdf",FileFormat.PDF);
}
}
效果图: