iText7 - 构建AcroForm字段层次结构的正确方法

时间:2016-07-28 15:29:51

标签: itext itext7

iText 7.0.0

有没有办法在iText7中构建字段层次结构而无需直接操作Fields字典?虽然PdfFormField有setParent / addKid方法,但我还没有找到可以生成的AcroForm.addField和setParent / addKid的正确组合/序列(希望这种语法有意义):

/Fields [(
     /T root 1 0 ("empty" field)
     /Kids [(
          /T child 2 0 ("empty" field)
          /Parent 1 0
          /Kids [(
               /T text1   (text widget)
               /FT Txt
               /Type /Annot
               /Subtype /Widget
               /Parent 2 0
          )]
      )]
 )]

即。名为root.child.text1

的字段

最接近的(对于某些indirectRef场景不起作用)是

    PdfFormField root = PdfFormField.createEmptyField(doc);
    root.setFieldName("root");
    form.addField(root, null);
    PdfFormField child = PdfFormField.createEmptyField(doc);
    child.setFieldName("child");
    form.addField(child, null);
    root.addKid(child);
    PdfTextFormField text1 = PdfFormField.createText(doc, new Rectangle(100, 700, 200, 20), "text1", "");
    // any rendered field needs to be added to the form BEFORE parent 
    // is set, otherwise an exception is thrown in processKids()
    form.addField(text1);
    child.addKid(text1);
    // cleanup the Fields dict
    PdfArray rootFields = form.getPdfObject().getAsArray(PdfName.Fields);
    rootFields.remove(text1.getPdfObject());
    rootFields.remove(child.getPdfObject());

1 个答案:

答案 0 :(得分:0)

尝试以下列方式接近。这个代码适用于我,至少在当前的7.0.1-SNAPSHOT版本中,因此它将在7.0.1中工作,这将在未来几周内完成。

您不必直接将每个字段添加到表单中。根据规范,只有根字段,即没有祖先的字段,必须添加到表单中。他们的后代会被自动考虑在内。

PdfFormField root = PdfFormField.createEmptyField(pdfDoc);
root.setFieldName("root");

PdfFormField child = PdfFormField.createEmptyField(pdfDoc);
child.setFieldName("child");
root.addKid(child);

PdfTextFormField text1 = PdfFormField.createText(pdfDoc, new Rectangle(100, 700, 200, 20), "text1", "test");
child.addKid(text1);

form.addField(root);