1 最近项目中需求根据合同模板生成正式的PDF合同,即将客户信息填充到合同模板上 开声称正式的合同
2. 工具:PDF模版中占位符需要使用(AdobeAcrobatproDC_pjb_3987)工具 将模版占位符替换成文本域
2.1 使用工具打开模版文件 点击 – 准备菜单
2.2 右键 -- 文本域
2.3 选中文本域 -- 右键 -- 属性 -- 把占位符key输入 选择只读
3 代码
`
// 获取项目部署的根目录
String WEBROOTPATH = Thread.currentThread().getContextClassLoader().getResource("").getPath();
logger.debug("如果目录不存在,创建文件夹..");
File file = new File(path);
if (!file.exists() && !file.isDirectory()) {
file.mkdir();
}
String desFile;// 正式pdf保存路径
String srcFile ;// 合同模版的路径
PdfReader reader = null;
PdfStamper stamper = null;
ByteArrayOutputStream bos = null;
FileOutputStream fos = null;
try {
BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);// 防止中文乱码
reader = new PdfReader(srcFile);
bos = new ByteArrayOutputStream();
stamper = new PdfStamper(reader, bos);
AcroFields form = stamper.getAcroFields();
form.addSubstitutionFont(bf);
// 1、替换表单元素中的变量为具体的值
for (Iterator<String> it = form.getFields().keySet().iterator(); it.hasNext();) {
String name = (String) it.next();
form.setField(name, paraMap.get(name));
form.setFieldProperty(name, "textfont", bf, null);
}
// 这两步必须有,否则pdf生成失败
stamper.setFormFlattening(false);
stamper.close();
// 生成填充完成的PDF合同文件
fos = new FileOutputStream(desFile);
fos.write(bos.toByteArray());
} catch (FileNotFoundException e) {
logger.error("FileNotFoundException, srcFile==" + srcFile, e);
} catch (Exception e) {
logger.error("Exception, srcFile==" + srcFile, e);
} finally {
if (null != reader) {
reader.close();
}
try {
if (null != bos) {
bos.close();
}
} catch (IOException e) {
logger.info("关闭ByteArrayOutputStream失败", e);
}
try {
if (null != fos) {
fos.close();
}
} catch (IOException e) {
logger.info("关闭FileOutputStream失败", e);
}
}
deleteFile(srcFile);
/**
* 删除文件
* @param fileName
*/
public static void deleteFile(String fileName) {
File f = new File(fileName);
if (f.exists()) {
f.delete();
}
4 到这里 你的文件中占位符就会替换成正式的数据 生成正式的合同了
5 附上 Java PDF 相关依赖
<!-- pdf begin -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.4.1</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
<!-- pdf end -->