今天用 itext 操作 pdf, 测试的时候还是成功的, 用到业务中就无效了, 表单内容填不进去, 代码如图
public class Test{
public static void main(String[] args) {
// m2() 是操作测试文件
m2();
// m3() 是操作实际要用的文件
m3();
}
public static void m2(){
Map<String, Object> form = new HashMap<>();
form.put("name", "xxx");
form.put("time", "xxx");
form.put("hobby", "on");
String templatePath = "C:\\Users\\Administrator\\Desktop\\test.pdf";
String targetPath = "C:\\Users\\Administrator\\Desktop\\test-out.pdf";
// 调用封装好的方法
FileUtils.generatePdfFromTemp(templatePath, targetPath, form);
}
public static void m3(){
Map<String, Object> form = new HashMap<>();
form.put("Lock Confirmed Date", "xxx");
form.put("Locked By", "xxx");
form.put("test", "xxx");
String templatePath = "C:\\Users\\Administrator\\Desktop\\template.pdf";
String targetPath = "C:\\Users\\Administrator\\Desktop\\target.pdf";
// 调用封装好的方法
FileUtils.generatePdfFromTemp(templatePath, targetPath, form);
}
}
/**
* 被调用的 generatePdfFromTemp () 方法
*/
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();
}
}
}
解决方案:
经过对比, 发现两份 pdf 模板的表单格式不一样, 如图
能够使用 itext 正常操作表单的 pdf 模板:
不能够使用 itext 正常操作表单的 pdf 模板:
把模板中的字体大小改成自动, 字体改成 Helvetica 就行了, 应该还有很多可用字体, 大家可以按需尝试;
原因:
未知