最近公司有个打印文件的需求,既然是打印,为了格式统一肯定使用PDF文件比较好,查了一下JAVA中大部分是使用IText创建PDF的,学习了下他人的方法,最终实现根据Freemarker模板生成PDF的方法
依赖
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.28</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.11</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.itextpdf.tool/xmlworker -->
<dependency>
<groupId>com.itextpdf.tool</groupId>
<artifactId>xmlworker</artifactId>
<version>5.5.11</version>
</dependency>
实际代码
freemarker模板文件 template.ftl
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<title>Title</title>
<style>
body {
font-family: SimHei;
}
.blue {
color: blue;
}
</style>
</head>
<body>
<div class="blue">
你好111,${name}
<ul>
<#list models as o>
<li>${o.uuid}</li>
</#list>
</ul>
</div>
</body>
</html>
根据freemarker模板生成HTML
public static String freeMarkerRender(Map<String, Object> data, String url, String htmlTmp) {
Writer out = new StringWriter();
try {
freemarkerCfg.setDirectoryForTemplateLoading(new File(url));
freemarkerCfg.setDefaultEncoding("UTF-8");
// 获取模板,并设置编码方式
Template template = freemarkerCfg.getTemplate(htmlTmp);
template.setEncoding("UTF-8");
// 合并数据模型与模板
template.process(data, out); //将合并后的数据和模板写入到流中,这里使用的字符流
out.flush();
return out.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
return null;
}
根据HTML生成PDF文件
public static void createPdf(OutputStream out, String content, String dest) throws IOException, DocumentException {
// step 1
Document document = new Document();
// step 2
PdfWriter writer = PdfWriter.getInstance(document, out);
// step 3
document.open();
// step 4
XMLWorkerFontProvider fontImp = new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS);
fontImp.register(FONT);
XMLWorkerHelper.getInstance().parseXHtml(writer, document,
new ByteArrayInputStream(content.getBytes("UTF-8")), null, Charset.forName("UTF-8"), fontImp);
// step 5
document.close();
}
测试代码
private static final String HTML = "PaperTemplate.ftl";
private static final String FONT = "C:\\app\\simhei.ttf";
@RequestMapping("/download/{id}")
@ResponseBody
public Object download(@PathVariable Long id, HttpSession httpSession) throws IOException, DocumentException {
Map<String, Object> data = new HashMap<>();
data.put("name", "张三");
data.put("model", paperServ.getAll());
String url = httpSession.getServletContext().getRealPath("/") + "download" + File.separator;
String html = freeMarkerRender(data, url, HTML);
ServletOutputStream out = getResponse().getOutputStream();
createPdf(out, html, DEST);
out.flush();
IOUtils.closeQuietly(out);
return html;
}
效果图