Why are the AcroFields in my document empty?

Tags: formsInspect fieldsbroken formiText 7

I have a PDF form with filled out fields. I can change the values and save them. But when I try to read the AcroFields, they are empty.

var reader = new PdfReader((DataContext as PDFContext).Datei);
AcroFields form = reader.AcroFields;
txt.Text = GetFormFieldNamesWithValues(reader);
 
private static string GetFormFieldNamesWithValues(PdfReader pdfReader) {
    return string.Join("\r\n", pdfReader.AcroFields.Fields
        .Select(x => x.Key + "=" +
        pdfReader.AcroFields.GetField(x.Key)).ToArray());
}
How can I read the fields?

Posted on StackOverflow on Apr 7, 2014 by Gregor Glinka

Clearly your PDF is broken. The fields are defined as widget annotations on the page level, but they aren't referenced in the /AcroForm fields set on the document root level.

You can fix your PDF in iText 7 using this code sample:

PdfReader reader = new PdfReader(imgSrc);
PdfDocument pdfDoc = new PdfDocument(reader, new PdfWriter(dest));
PdfCatalog root = pdfDoc.getCatalog();
PdfDictionary form = root.getPdfObject().getAsDictionary(PdfName.AcroForm);
PdfArray fields = form.getAsArray(PdfName.Fields);
PdfPage page;
List<PdfAnnotation> annots;
for (int i = 1; i <= pdfDoc.getNumberOfPages(); i++) {
    page = pdfDoc.getPage(i);
    annots = page.getAnnotations();
    for (int j = 0; j < annots.size(); j++) {
        fields.add(annots.get(j).getPdfObject());
    }
}
pdfDoc.close();

You should inform the creators of the tool that was used to produce the form that their PDFs aren't compliant with the PDF reference.

Click this link if you want to see how to answer this question in iText 5.