首页 文章

itext AcroFields表单到第二页,需要保留相同的模板

提问于
浏览
2

我有一个我在MS Word中创建的表单然后转换为PDF(表单)然后我使用PDF阅读器加载它,然后我创建了一个填充字段的压模,如果我想添加第二页与相同的模板(Form)我该怎么做并用相同的信息填充一些字段

我已经设法与另一个读者获得一个新页面,但我如何在此页面上标记信息,因为AcroFields将具有相同的名称 . #

这就是我实现的目标:

stamper.insertPage(1,PageSize.A4);
        PdfReader reader = new PdfReader("/soaprintjobs/templates/STOTemplate.pdf"); //reads the original pdf
        PdfImportedPage page; //writes the new pdf to file 
        page = stamper.getImportedPage(reader,1); //retrieve the second page of the original pdf
        PdfContentByte newPageContent = stamper.getUnderContent(1); //get the over content of the first page of the new pdf
        newPageContent.addTemplate(page, 0,0);

谢谢

1 回答

  • 2

    Acroform字段具有将具有相同名称的字段视为相同字段的属性 . 它们具有相同的 Value . 因此,如果您在第1页和第2页上有一个具有相同名称的字段,它们将始终显示相同的值 . 如果更改第1页上的值,它也将在第2页上更改 .

    在某些情况下,这是可取的 . 您可能有一个带有参考编号的多页表格,并希望在每页上重复该参考编号 . 在这种情况下,您可以使用具有相同名称的字段 .

    但是,如果您希望在1个文档中使用同一表单的多个副本和不同的数据,则会遇到问题 . 您必须重命名表单字段,以使它们是唯一的 .

    在iText中,您不应使用 getImportedPage() 来复制Acroforms . 从iText 5.4.4开始,您可以使用 PdfCopy 类 . 在早期版本中,应使用 PdfCopyFields 类 .

    以下是复制Acroforms和重命名字段的示例代码 . iText 5.4.4及以上代码在评论中 .

    public static void main(String[] args) throws FileNotFoundException, DocumentException, IOException {
    
        String[] inputs = { "form1.pdf", "form2.pdf" };
    
        PdfCopyFields pcf = new PdfCopyFields(new FileOutputStream("out.pdf"));
    
        // iText 5.4.4+
        // Document document = new Document();
        // PdfCopy pcf = new PdfCopy(document, new FileOutputStream("out.pdf"));
        // pcf.setMergeFields();
        // document.open();
    
        int documentnumber = 0;
        for (String input : inputs) {
            PdfReader reader = new PdfReader(input);
            documentnumber++;
            // add suffix to each field name, in order to make them unique.
            renameFields(reader, documentnumber);
            pcf.addDocument(reader);
        }
        pcf.close();
    
        // iText 5.4.4+
        // document.close();
    
    }
    
    public static void renameFields(PdfReader reader, int documentnumber) {
        Set<String> keys = new HashSet<String>(reader.getAcroFields()
                .getFields().keySet());
        for (String key : keys) {
            reader.getAcroFields().renameField(key, key + "_" + documentnumber);
        }
    }
    

相关问题