iText7 setValue method not working

江枫思渺然 提交于 2019-12-08 13:15:01

问题


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



来源:https://stackoverflow.com/questions/40712084/itext7-setvalue-method-not-working

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!