【问题标题】:Unable to open pdf after creation创建后无法打开pdf
【发布时间】:2021-12-10 11:49:08
【问题描述】:

我正在编写一个程序,它获取带有一堆空白表单域的模板 PDF,复制它,填写表单,然后展平这些域。

其中一个模板有大量字段,因此编写一个填充所有字段的方法会导致错误,指出由于方法的大小限制,代码太大。

为了解决这个问题,我关闭了目标文件,然后尝试用另一种方法打开它,我可以继续填写字段,但这会导致错误提示“(无法对文件执行请求的操作打开用户映射部分)"

我通过关闭 PDF 结束了第一种方法,所以我不确定问题是什么。程序将执行第一个方法,填充字段,但在执行第二个方法时抛出错误。示例代码如下。

public void E2fill(String srcE2, String destE2) throws IOException
{
    try
    {
        PdfDocument pdf2 = new PdfDocument(new PdfReader(destE2), new PdfWriter(dest2E2));
        PdfAcroForm form2 = PdfAcroForm.getAcroForm(pdf2, true);
        Map<String, PdfFormField> fields2 = form2.getFormFields();
        PdfFormField field2;
        fields2.get("fieldname1").setValue(stringname1);
        //lots more field fills
        pdf2.close()
    }
    catch(Exception x)
    {
        System.out.println(x.getMessage());
    }
}

public void E2fill2(String destE2, String dest2E2) throws IOException
{
    try
    {
        PdfDocument pdf2 = new PdfDocument(new PdfReader(destE2), new PdfWriter(dest2E2));
        PdfAcroForm form2 = PdfAcroForm.getAcroForm(pdf2, true);
        Map<String, PdfFormField> fields2 = form2.getFormFields();
        PdfFormField field2;
        fields2.get("fieldname546").setValue(stringname546);
        //more field fills
        form2.flattenFields();
        pdf2.close();
    }
    catch(Exception x)
    {
        System.out.println(x.getMessage());
    }
}

【问题讨论】:

  • 不用关闭pdf文件,只需将pdf2form2作为参数传递给E2fill2
  • 创建多个方法而不是一个方法并按顺序调用它们
  • 不关闭 pdf 并将参数传递给 E2fill2 会导致“线程“主”com.itextpdf.io.IOException 中的异常:未找到 PDF 标头。”错误
  • @tgdavies 您可能应该让您的提案成为更详细的答案,因为 Gareth 显然无法成功实施它。

标签: java pdf itext itext7


【解决方案1】:

我建议你试试这个:

    public void fill(String srcE2, String destE2) {
        PdfDocument pdf2 = new PdfDocument(new PdfReader(destE2), new PdfWriter(dest2E2));
        PdfAcroForm form2 = PdfAcroForm.getAcroForm(pdf2, true);
        Map<String, PdfFormField> fields2 = form2.getFormFields();
        E2fill(fields2);
        E2fill2(fields2);
        form2.flattenFields();
        pdf2.close();
    }

    public void E2fill(Map<String, PdfFormField> fields2) throws IOException 
    {
        fields2.get("fieldname1").setValue(stringname1);
        //lots more field fills
    }

    public void E2fill2(PdfAcroForm form2) throws IOException {
        fields2.get("fieldname546").setValue(stringname546);
        //more field fills
    }

【讨论】:

  • 谢谢!我在您的其他评论中误解了您的建议。构建这样的东西非常有效
  • 很高兴为您提供帮助 :-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-19
相关资源
最近更新 更多