制作模板
首先需要安装Adobe Acrobat DC来制作模板
打开dc工具——》准备表单,然后打开你需要制作的pdf源文件
将文本域拖到你需要代码替换的位置
你可以双击文本域修改当前文本域的key值,便于代码中替换
也可以修改文本域的字体大小以及颜色等,在外观这一栏下
设置好文本域之后保存,如果发现保存之后一直卡住,可以按如下操作,打开编辑——》首选项
点击一般,将红框内的在线存储取消掉即可
程序实现
依赖包
将制作好的模板文件放在resources目录下
/**
* 根据模板生成pdf
*
* @param contract
* @return
*/
@SneakyThrows
public void createPDF(ContractData contract, HttpServletResponse response) {
PdfReader reader = null;
AcroFields s = null;
PdfStamper ps = null;
ByteArrayOutputStream bos = null;
try {
ClassPathResource resource = new ClassPathResource("contractTemplate.pdf");
InputStream is = resource.getInputStream();
reader = new PdfReader(is);
bos = new ByteArrayOutputStream();
ps = new PdfStamper(reader, bos);
s = ps.getAcroFields();
Class clazz = ContractData.class;
Field[] fields = clazz.getDeclaredFields();
try {
for (Field f : fields) {
f.setAccessible(true);
if (f.get(contract) != null) {
s.setField(f.getName(), f.get(contract).toString());
}
}
} catch (IllegalAccessException e) {
throw new CommonException();
}
// 如果为false那么生成的PDF文件还能编辑,一定要设为true
ps.setFormFlattening(true);
ps.close();
response.reset();
response.setContentType("application/pdf");
ServletOutputStream fos = response.getOutputStream();
fos.write(bos.toByteArray());
fos.flush();
fos.close();
} catch (IOException | DocumentException e) {
e.printStackTrace();
} finally {
try {
bos.close();
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
核心代码
@Data
class ContractData {
private String contractNo;
private String partyAName;
private String partyBName;
}
实体类
这样就可以了
下面是生成的最终pdf文件
最后生成的效果
大功告成~