1 准备一份pdf
2 使用 adobe acrobat pro 添加表单区域
软件会自动猜测一些表单域, 比如这两个下划线;
也可以手动添加表单域, 不需要提前设置下划线;
双击可以修改里面的值, 我改为了 name 和 time;
添加好后保存;
保存之后, 选择”高亮域” 可以看见pdf变成了这个样子
3 这样 pdf 就准备好了, 下面开始用 java 读取这份 pdf 模板并填表单;
添加依赖
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.4.3</version>
</dependency>
3.1 测试代码:
public static void main(String[] args){
String templatePath = "C:\\Users\\Administrator\\Desktop\\test.pdf";
String targetPath = "C:\\Users\\Administrator\\Desktop\\test-output.pdf";
// 模板 pdf 文件
PdfReader template = null;
// 目标 pdf 文件
PdfStamper target = null;
try {
// 获取模板 pdf 文件
template = new PdfReader(templatePath);
// 创建目标 pdf 文件
File targetFile = new File(targetPath);
target = new PdfStamper(template, new FileOutputStream(targetFile));
/*
程序执行到这里, 已经创建了目标的 pdf 文件, 相当于把 template 复制到了 target 中;
target 文件处于被操作状态, 不可由外部应用打开
*/
// 取出 target 中的表单
AcroFields form = target.getAcroFields();
// 填充数据
form.setField("name", "zhangsan");
form.setField("time", LocalDateTime.now().toString());
// false: 生成的PDF文件可以编辑; true: 生成的PDF文件不可以编辑
target.setFormFlattening(true);
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭 target 文件, 分开关闭, 如果 target.close() 发生错误, 能保证 template.close() 仍可执行
if (target != null) {
try {
target.close();
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
// 程序执行到这里, 已经结束了对 target 文件的操作并且关闭了流通道
// 外部应用从此刻起, 可以打开 target 文件
// 关闭 template 文件
if (template != null) {
template.close();
}
}
}
执行效果图:
填充的 zhangsan 和 2021-6-7T17:50:27会根据表单给的空间自动放缩大小, 按需调整;
3.2 简单封装版代码:
public class FileUtils {
private FileUtils(){}
/**
* 以本地的 pdf 文件为模板, 生成目标 pdf 文件到本地
* @param templatePath 本地的 pdf 文件路径
* @param targetPath 目标 pdf 文件路径
* @param data 表单数据, 只支持文本数据, 不支图片等数据
*/
public static void generatePdfFromTemp(String templatePath, String targetPath, Map<String, ? extends Object> data){
PdfReader template = null;
PdfStamper target = null;
try {
template = new PdfReader(templatePath);
File targetFile = new File(targetPath);
target = new PdfStamper(template, new FileOutputStream(targetFile));
AcroFields form = target.getAcroFields();
for (Map.Entry<String, ?> entry : data.entrySet()) {
form.setField(entry.getKey(), entry.getValue().toString());
}
target.setFormFlattening(true);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (target != null) {
try {
target.close();
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
if (template != null) {
template.close();
}
}
}
}