废话少说,直接上代码:
Maven:
<dependency>
<groupId>org.xhtmlrenderer</groupId>
<artifactId>flying-saucer-pdf-itext5</artifactId>
<version>9.1.5</version>
</dependency>
Java:
OutputStream os = null;
try {
os = new FileOutputStream(outputFile);
ITextRenderer renderer = new ITextRenderer();
ITextFontResolver fontResolver = renderer.getFontResolver();
//中文问题解决,将字体文件simsun.ttc 放到resources\fonts 目录下
fontResolver.addFont(App.class.getClassLoader().getResource("fonts\\simsun.ttc").toURI().toString(), BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
String htmlStr="这里是freemarker模板引擎解析出来的html代码";
renderer.setDocumentFromString(htmlStr);
// 图片显示问题解决,html代码中img src 用相对路径
renderer.getSharedContext().setBaseURL(App.class.getClassLoader().getResource("").toURI().toString());
renderer.layout();
renderer.createPDF(os);
//完成创建,自动关闭Document资源
renderer.finishPDF();