前言
使用html页面改成ftl模板,生成PDF,并对生成的PDF进行加密
一、Ftl模板制作
1.编写HTML标签
示例如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head lang="en">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>1212</title>
<style type="text/css">
/*解决html转pdf文件中文不显示的问题*/
body {
font-family: "Microsoft YaHei";
font-size: 7pt;
line-height: 17pt;
}
.imgdev {
width: 100%;
display: inline-block;
}
.headerdev {
width: 100%;
}
</style>
</head>
<body>
<div class="imgdev">
<img src="${logo1}" width="310" height="72"/>
<div style="color: #555">
<div>${info1}</div>
<div>${info2}</div>
<hr style="background-color: #888;height: 1px"/>
<div style="fontWeight: 600">${com}</div>
<div style="fontWeight: 700">${comen}</div>
</div>
</div>
<div class="headerdev">
${context}
<br/>
<img src="${auto}" width="90" height="42" style="padding-left: 50px"/>
<img src="${auto2}" width="100" height="80"/>
<div class="line"></div>
<p>${title}</p>
</div>
</body>
</html>
2.修改文件后缀,把html改成ftl
二、生成PDF并加密
1.引入jar包
<!-- spring boot 项目请添加此依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<!-- 非spring boot 项目请添加此依赖 -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.30</version>
</dependency>
<!-- 对生成的PDF加密的jar -->
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.office.free</artifactId>
<version>2.2.0</version>
</dependency>
2.关键代码
代码如下:
public class PDFTest {
private static String path ="Y:\\1";
/**
* 生成PDF并加密
*/
@org.junit.jupiter.api.Test
public byte[] test()
{
Configuration configuration = new Configuration();
configuration.setDefaultEncoding("UTF-8");
//构建PDF需要替换的值
Map psnMap = (Map) this.getFormInfo(pk, visa);
Map map = this.dataDownPdfQuery(psnMap);
String templateName="1.ftl";
configuration.setDirectoryForTemplateLoading(new File(path));
Template templatehtml = configuration.getTemplate(templateName);
File file = new File(templateName);
StringWriter writer = new StringWriter();
templatehtml.process(map, writer);
writer.flush();
OutputStream os = null;
File files=new File(path + File.separator + templateName.replace(".ftl", ".pdf") );
os = new FileOutputStream(files);
ITextRenderer renderer = new ITextRenderer();
renderer.setDocumentFromString(writer.toString());
ITextFontResolver fontResolver = renderer.getFontResolver();
fontResolver.addFont(path + File.separator+"fonts/mcyahei.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
renderer.layout();
renderer.createPDF(os);
os.close();
//上半段是生成PDF,下半截是对生成的PDF进行设置密码加密
//创建PdfDocument实例
PdfDocument doc = new PdfDocument();
//加载PDF文件
doc.loadFromFile(files.getAbsolutePath());
doc.getPages().add();
//对文件进行加密
PdfEncryptionKeySize keySize = PdfEncryptionKeySize.Key_128_Bit;
String date="20221222"
String openPassword = date;//打开文档时,仅用于查看文档
String permissionPassword = date;//打开文档时,可编辑文档
EnumSet flags = EnumSet.of(PdfPermissionsFlags.Print, PdfPermissionsFlags.Fill_Fields);
doc.getSecurity().encrypt(openPassword, permissionPassword, flags, keySize);
doc.getPages().remove(doc.getPages().get(doc.getPages().getCount()-1));
//保存文件
doc.saveToFile(files.getAbsolutePath());
doc.close();
return EntryFileConfiguration.fileToBytes(files);
}
}
注意注意!
如果内容中出现了特殊符号记得用转义符替换,&换&
// 获取相应的需要替换的内容
Iterator<Entry<String, Object>> map1it = map.entrySet().iterator();
while (map1it.hasNext()) {
Map.Entry<String, Object> entry = (Entry<String, Object>) map1it
.next();
if (!(entry.getValue() instanceof List)) {
if (entry.getValue() != null
&& entry.getValue().toString().contains("&")) {
String newValue = entry.getValue().toString().replace("&", "&");
map.put(entry.getKey(), newValue);
}
if (entry.getValue() != null&& entry.getValue().toString().contains("<")) {
String newValue = entry.getValue().toString().replace("<", "<");
map.put(entry.getKey(), newValue);
}
} else {
for (Object childMap : (List) entry.getValue()) {
if (childMap != null && (childMap instanceof Map)) {
Map<String, Object> child = (Map<String, Object>) childMap;
for (Entry<String, Object> childEntry : child.entrySet()) {
if (childEntry.getValue() == null) {
continue;
}
if (childEntry.getValue().toString().contains("&")) {
String newValue = childEntry.getValue().toString().replace("&", "&");
child.put(childEntry.getKey(), newValue);
}
if (childEntry.getValue().toString().contains("<")) {
String newValue = childEntry.getValue().toString().replace("<", "<");
child.put(childEntry.getKey(), newValue);
}
}
}
}
}
总结
本文仅仅简单介绍了通过ftl模板生成PDF的使用,而使用spire.office.free jar提供了大量能使我们快速便捷地处理PDF加密解密的方法,继续探究冲冲冲!