本来项目中想要使用playframework中自身的pdf模块实现html转换为pdf的功能,但是发现目前该模块对中文乱码和中文换行支持的不是很好,只能抛弃了附件中会提供本次开发中需要使用到的几个JAR包方便大家开发时使用。
public static String createPDF(String fileName,String content){
fileName = StringUtil.trim(fileName);
String fontPath=ContextUtil.getProperty("font.path");//在配置文件中指定字体的路径
String filePath = ContextUtil.getProperty("pdf.path", "/public/download/");//生成的PDF文件存放的路径
File f = Play.getFile(filePath+fileName+".pdf");
try {
OutputStream os = new FileOutputStream(f);
ITextRenderer tRend = new ITextRenderer();
ITextFontResolver fontResolver = tRend.getFontResolver();
fontResolver.addFont(fontPath, BaseFont.IDENTITY_H,BaseFont.EMBEDDED);
tRend.setDocumentFromString(content);
tRend.layout();
tRend.createPDF(os);
os.close();
} catch (FileNotFoundException e) {
ExceptionHandler.throwRuntimeException(e, "生成PDF文件时文件路径不存在", logger);
} catch (DocumentException e) {
ExceptionHandler.throwRuntimeException(e, "生成PDF文件时设置文件内容时出错", logger);
} catch (IOException e) {
ExceptionHandler.throwRuntimeException(e, "生成PDF文件时文件流关闭时出错", logger);
}
return f.getAbsolutePath();
}
在application.conf中增加以下内容:
font.path=file:/usr/share/fonts/simsun.ttc
pdf.path=/public/download/
页面中增加的样式内容:
<style type="text/css">
body {
font-size: 12px;
font-family: SimSun;
}
</style>