freemark生成pdf
字体库 simsun.ttc 解决中文问题
/**
* 生成pdf
* @param params
* @param templPath
* @param ftlName
* @param htmlPath
* @param pdfPath
* @param fontPath
* @return
*/
public String processPdf(Map<String, Object> params, String templPath, String ftlName, String htmlPath,
String pdfPath, String fontPath) {
// 得到模板地址
try {
configuration.setDirectoryForTemplateLoading(new File(templPath));
Template temp = configuration.getTemplate(ftlName);
File htmlFile = new File(htmlPath);
if (!htmlFile.exists()) {
htmlFile.createNewFile();
}
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(htmlPath)), "utf-8"));
temp.process(params, out);
out.flush();
String url = htmlFile.toURI().toURL().toString();
OutputStream os = new FileOutputStream(pdfPath);
ITextRenderer renderer = new ITextRenderer();
renderer.setDocument(url);
// 解决中文问题
ITextFontResolver fontResolver = renderer.getFontResolver();
fontResolver.addFont(fontPath + "simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
renderer.layout();
renderer.createPDF(os);
os.close();
} catch (Exception e) {
e.printStackTrace();
return "";
}
return pdfPath;
}
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
<version>${spring-boot-starter-freemarker.version}</version>
</dependency>
<dependency>
<groupId>com.lowagie</groupId>
<artifactId>itext</artifactId>
<version>2.0.8</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.0.6</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-xtra</artifactId>
<version>5.4.5</version>
</dependency>
<dependency>
<groupId>org.xhtmlrenderer</groupId>
<artifactId>core-renderer</artifactId>
<version>8.0</version>
</dependency>