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
在html文件頭部須要指定字體:app
<style>字體
body {font-family:SimSun;}//字體htm
@page{size: 11.69in 8.27in;}//字體及頁面大小圖片
</style>get
注:生成pdf文件的html文件必須遵循嚴格的html格式。有開始標籤就必須有相應的閉合標籤!io