首页 > 技术文章 > HTML转PDF

tuya 2014-01-14 17:13 原文

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("\r\n");
}
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格式。有开始标签就必须有相应的闭合标签!

 

推荐阅读