itext写入PDF,写不进去,就是复制了模板, [解决]

本文探讨了使用iText操作PDF时,为何测试通过但在实际应用中表单填写失败。关键在于识别了两个模板的格式差异,发现调整字体大小和类型(如Helvetica)能解决问题。解决策略在于检查并确保PDF表单结构与工具兼容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天用 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 就行了, 应该还有很多可用字体, 大家可以按需尝试;

原因:

未知

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值