本文将介绍如何使用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);
}
}
效果图: