iText7 setValue method not working

2019-06-13 18:39发布

问题:

I am trying to add a form to a pdf using iText 7.

I keep getting an error when trying to set the value of the field. I haven't been able to find information from the documentation of the addKid() method. Does anyone know how to get around this error?

Here's a sample of the code I'm using:

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
}

回答1:

I presume the error you are getting is this PdfException: Exception in thread "main" com.itextpdf.kernel.PdfException: Object must be indirect to work with this wrapper`?

The solution is to mark you annotations as indirect after creating them:

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);

Explanation: When setting the values of form fields in iText7, it expects the annotations to be indirect objects and will raise an exception when they aren't. Since PdfWidgetAnnotationis created independently from the PdfDocument, the link needs to be specified explicitly by calling makeIndirect()



标签: java pdf itext7