HTML转PDF

public static void main(String[] args) {
StringBuffer sb = new StringBuffer();
String path = "C:\Windows\Fonts\simsun.ttc";//字体文件。必须要。不然无法显示中文
try {
BufferedReader reader = new BufferedReader(new FileReader(new File("D:\123\abc.html")));//需要生成pdf的html文件
String line = null;
while((line = reader.readLine()) != null){
sb.append(line).append(" ");
}
ITextRenderer render = new ITextRenderer();
ITextFontResolver font = render.getFontResolver();
font.addFont(path, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
OutputStream out = new FileOutputStream(new File("D:\wasapp\miclm\photo\20140110\700029151\cache\outCache103.pdf"));//生成后的pdf文件
render.setDocumentFromString(sb.toString());
render.getSharedContext().setBaseURL("file:\D:\123\");//设置图片html文件中图片的路径。需要在“123”文件夹下有html文件中需要的图片
render.layout();
render.createPDF(out);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
}

在html文件头部需要指定字体:

<style>

body {font-family:SimSun;}//字体

@page{size: 11.69in 8.27in;}//字体及页面大小

</style>

注:生成pdf文件的html文件必须遵循严格的html格式。有开始标签就必须有相应的闭合标签!

原文地址:https://www.cnblogs.com/tuya/p/3519432.html