freemark生成pdf
字体库 simsun.ttc 解决中文问题文章来源:https://www.toymoban.com/news/detail-547704.html
/**
* 生成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>
文章来源地址https://www.toymoban.com/news/detail-547704.html
到了这里,关于freemark生成pdf的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!