iText7 setValue方法不起作用

我正在尝试使用iText 7将表单添加到pdf。

尝试设置字段的值时,我一直收到错误。 我无法从addKid()方法的文档中找到信息。 有谁知道如何解决这个错误?

这是我正在使用的代码示例:

 PdfTextFormField confField = PdfFormField.createText(pdf); confField.setFieldName(fieldName); PdfWidgetAnnotation confCoverAnnot = new PdfWidgetAnnotation(new Rectangle(x, y, width, height)); PdfWidgetAnnotation confAnnot = new PdfWidgetAnnotation(new Rectangle(x2, y2, width2, height2)); for (int i = 1; i<= numPages; i++) { switch(i) { case 1: pdf.getPage(i).addAnnotation(confCoverAnnot); break; default: pdf.getPage(i).addAnnotation(confAnnot); break; } } /* Trying to have two different annotations reference the same field value. Upon using the `setValue()` method, I get: object.must.be.indirect.to.work.with.this.wrapper Any way to get this to work properly? */ form.addField(confField); confField.addKid(confCoverAnnot); confField.addKid(confAnnot); if (value.equals("") != true) { confField.setValue(value); //error here } 

我假设你得到的错误是这个PdfException :线程“main”中的exceptioncom.itextpdf.kernel.PdfException:对象必须是间接的才能使用这个包装器吗?

解决方案是在创建注释后将注释标记为间接注释:

 PdfWidgetAnnotation confCoverAnnot = new PdfWidgetAnnotation(new Rectangle(x, y, width, height)); confCoverAnnot.makeIndirect(pdf); PdfWidgetAnnotation confAnnot = new PdfWidgetAnnotation(new Rectangle(x, y, width, height)); confAnnot.makeIndirect(pdf); 

说明:在iText7中设置表单字段的值时,它期望注释是间接对象,并且当它们不是时会引发exception。 由于PdfWidgetAnnotation是独立于PdfWidgetAnnotation创建的,因此需要通过调用makeIndirect()显式指定链接。