Until now, every PDF InvoiceLab produced was a finished document: invoices, delivery notes and batches that get read, printed or, at most, stamped. But many of the PDFs that circulate in a company are made for someone to write in them: applications, orders, surveys, authorisations. These are PDF forms. Nebula Distribution has a very specific one: the Customer registration form, a fillable PDF that new customers download, complete with their tax details, payment method and acceptance of the terms, and send back by email. In this module InvoiceLab will learn to read those forms, prefill them, create them from scratch and archive them. In this first lesson we won't fill in anything yet: we're going to understand how a form is built on the inside (the AcroForm dictionary, fields, widgets, their names, types and flags), and we'll finish with a tool, FormInspector, that takes an inventory of any form that lands on our desk.

Contents

  1. What a PDF form is
  2. AcroForm versus XFA
  3. Our starting form: registration-form.pdf
  4. The AcroForm dictionary and the PDAcroForm class
  5. Fields and widgets: what's stored and what's shown
  6. Fully qualified names and the field hierarchy
  7. Field types in PDFBox
  8. Field flags: ReadOnly, Required and NoExport
  9. Default resources (/DR), default appearance (/DA) and NeedAppearances
  10. FormInspector: the inventory of a form

What a PDF form is

A PDF form is an ordinary document (pages, text, graphics) with interactive areas added where the user enters data: text boxes, checkboxes, radio buttons, drop-down lists or a space to sign. That data is stored inside the PDF itself, so the file travels with the information that was filled in.

For a business, this has clear advantages:

  • Customers can fill it in with any free viewer, without installing anything or signing up on a website.
  • The document keeps the corporate look (logo, legal text, layout).
  • The data can be extracted automatically: nobody has to retype the VAT ID or the address.
  • The same file serves as proof: it can be flattened, stamped and archived (lesson 05-04).

AcroForm versus XFA

There are two very different PDF form technologies:

AcroForm XFA (XML Forms Architecture)
Origin Part of the PDF standard since PDF 1.2 Adobe technology (LiveCycle Designer)
Where the fields live PDF objects: field dictionaries and widget annotations An XML package inside the PDF (/XFA)
Status in the standard Current in PDF 2.0 (ISO 32000-2) Deprecated: removed in PDF 2.0
Viewer support Universal (Acrobat, browsers, desktop and mobile viewers) Practically only Adobe Acrobat/Reader
PDFBox support Full: read, fill, create and flatten Only lets you read the XML; it doesn't fill in or render XFA

XFA itself comes in two flavours:

  • Static (or hybrid) XFA: the PDF contains the XML and, alongside it, equivalent AcroForm fields. Viewers that don't understand XFA use the AcroForm fields.
  • Dynamic XFA: the form is built at display time from the XML (pages can grow, sections can appear…). There are no AcroForm fields to fill in and, in non-Adobe viewers, you often see nothing more than a message along the lines of "please wait, the document is loading".

PDFBox lets you detect this with two PDAcroForm methods:

PDAcroForm form = document.getDocumentCatalog().getAcroForm(null);
if (form != null && form.hasXFA()) {                       // does the /XFA key exist?
    if (form.xfaIsDynamic()) {                             // XFA and no AcroForm fields
        System.out.println("Dynamic XFA: PDFBox can't fill it in");
    } else {
        System.out.println("Hybrid XFA: its AcroForm fields can be filled in");
    }
}
  • hasXFA() returns true if the AcroForm dictionary has the /XFA key.
  • xfaIsDynamic() returns true when there's XFA and no AcroForm fields at all. We've checked it: if you remove the fields from a form with /XFA, the method goes from false to true.
  • getXFA() returns a PDXFAResource with the XML (useful for inspecting it, not for filling it in).

Tip: with a hybrid form that you're going to fill in with PDFBox, it's common practice to remove the XML with form.setXFA(null) before saving. Otherwise, Acrobat may keep showing the data from the XML (which PDFBox hasn't touched) instead of the data in the AcroForm fields. With dynamic XFA there's no shortcut: you have to ask the sender for an AcroForm version or rebuild the form.

For the rest of the module we'll work exclusively with AcroForm, which is what the current standard recommends and what InvoiceLab will generate.

Our starting form: registration-form.pdf

To study a form we need one. We'll use Nebula Distribution's, which has six sections: company details, contact person, payment method, notes, terms and data protection, and signature; plus an area labelled "Reserved for Nebula Distribution".

This PDF is generated by the com.invoicelab.forms.GenerateRegistrationForm class, backed by a small field factory, PdfFields. Its complete code, explained step by step, is in lesson 05-03, where we'll learn how to create forms. To follow this lesson and the next one, do the following:

  1. Create the com.invoicelab.forms package.
  2. Copy PdfFields.java and GenerateRegistrationForm.java into it exactly as they appear in lesson 05-03. They only use classes you already have (InvoiceLabFonts, ContentBox, Theme, Shapes, TextMetrics, NebulaColors).
  3. Run GenerateRegistrationForm. You'll get output/registration-form.pdf.

For now, treat it as a black box, just as you would a form sent to you by another company: you don't need to know how it was made in order to analyse it. In fact, that's the most common real-world situation: the forms InvoiceLab will have to process will have been designed by other people, with other tools.

If you prefer, you can also practise with any public AcroForm form (for example, a downloadable government form). Everything we'll cover works with any form.

Open it in your viewer: you'll see boxes with a light blue background, a VAT ID and a postal code with one box per character, three radio buttons for the payment method, a list of provinces, three checkboxes and a box for the signature.

The AcroForm dictionary and the PDAcroForm class

The whole form hangs off a single entry in the catalog: /AcroForm. That dictionary contains the list of root fields and the shared configuration:

flowchart TD
    CAT["Catalog"] -->|"/AcroForm"| AF["AcroForm dictionary<br/>/Fields [ ... ]<br/>/DR (default resources)<br/>/DA (default appearance)<br/>/NeedAppearances"]
    AF -->|"/Fields"| C1["customer"]
    AF --> C2["contact"]
    AF --> C3["payment"]
    AF --> C4["notes"]
    AF --> C5["..."]
    CAT -->|"/Pages"| P["Page 1<br/>/Annots [ widgets ]"]

In PDFBox, that dictionary is a PDAcroForm and you get it from the catalog:

PDAcroForm form = document.getDocumentCatalog().getAcroForm(null);   // null if there's no form

Note the null argument. PDDocumentCatalog offers two variants:

Method What it does
getAcroForm() First applies some automatic fixes (fixups): for example, if the form has NeedAppearances set to true, it generates the missing appearances and sets the flag to false. It modifies the document in memory
getAcroForm(null) Returns the form exactly as it is in the file, without touching anything

We've checked it: a PDF saved with NeedAppearances = true returns true with getAcroForm(null) and false with getAcroForm(). To inspect a form, or to edit it with full control, we'll always use getAcroForm(null). The version with fixups is convenient for simple programs that only want to fill in and save, but it's worth knowing it exists.

The PDAcroForm methods we'll use most in this module:

Method What for
getFields() The root fields (those in /Fields), not all of them
getFieldTree() A full walk of the tree: roots, intermediate nodes and leaves
getField(String) Looks up a field by its fully qualified name
getDefaultResources() / getDefaultAppearance() /DR and /DA
getNeedAppearances() / setNeedAppearances(Boolean) The /NeedAppearances flag
hasXFA(), xfaIsDynamic(), getXFA(), setXFA(...) XFA
refreshAppearances(), flatten(), exportFDF(), importFDF(...) Lessons 05-02 and 05-04

Fields and widgets: what's stored and what's shown

The most important idea in AcroForm is that there are two different kinds of object:

  • The field (PDField): stores the name, the type, the value (/V) and the flags. It's what the data "is".
  • The widget (widget annotation, PDAnnotationWidget): a page annotation with a rectangle (/Rect), a page (/P) and an appearance (/AP). It's what "is shown" and where the user clicks.

A field can have one or more widgets. The typical case with several widgets is the radio group: the payment.method field is a single piece of data (the chosen payment method), but it's shown in three places (three buttons).

flowchart LR
    subgraph Case1["One widget: field and widget merged"]
        N["customer.taxId<br/>/FT /Tx  /V (J00000000)<br/>/Subtype /Widget  /Rect [...]  /AP"]
    end
    subgraph Case2["Several widgets: the field has /Kids"]
        F["payment.method<br/>/FT /Btn  /V /Transfer"] --> W1["Widget 1<br/>/AS /Transfer"]
        F --> W2["Widget 2<br/>/AS /Off"]
        F --> W3["Widget 3<br/>/AS /Off"]
    end

When a field has a single widget, the standard allows both to be merged into the same dictionary. That's what happens with customer.taxId; this is its actual content after being filled in (we dumped it with PDFBox):

/FT /Tx                 ← field type: text            (FIELD part)
/T (taxId)              ← partial name                (FIELD)
/Parent → customer      ← its parent in the tree      (FIELD)
/V (J00000000)          ← the value                   (FIELD)
/Ff 16777218            ← flags                       (FIELD)
/MaxLen 9               ← maximum length              (FIELD)
/DA (/Helv 10 Tf 0 g)   ← default appearance          (FIELD)
/Type /Annot            ← it's an annotation...       (WIDGET)
/Subtype /Widget        ← ...of the widget kind       (WIDGET)
/Rect [51 665 177 681]  ← where it sits on the page   (WIDGET)
/P → page 1             ← which page                  (WIDGET)
/AP << /N ... >>        ← how it's drawn              (WIDGET)
/MK << ... >>  /BS ...  ← colours and border          (WIDGET)

In the radio group, on the other hand, the payment.method field only has /FT, /Ff, /T, /V and /Kids; each of its three children is a widget with its own /Rect, its own /AP and its /AS state.

PDFBox hides this difference: field.getWidgets() always returns a list of PDAnnotationWidget, whether it's the merged dictionary itself or the children. In addition, each widget appears in the /Annots array of its page, which is how the viewer knows what to draw on it.

Practical consequence: the value is read from and written to the field; the position and the page are looked up in the widgets.

Fully qualified names and the field hierarchy

Fields are organised in a tree. Intermediate nodes (PDNonTerminalField) have no widgets and no type of their own: they only group. The leaves (PDTerminalField) are the actual fields.

Each field has a partial name (/T), and its fully qualified name is formed by joining the partial names from the root with dots:

flowchart TD
    R["/Fields"] --> CL["customer"]
    R --> CO["contact"]
    R --> PA["payment"]
    R --> OB["notes (Tx)"]
    CL --> RS["companyName (Tx)"]
    CL --> NIF["taxId (Tx)"]
    CL --> DI["address"]
    DI --> VIA["street (Tx)"]
    DI --> CP["postalCode (Tx)"]
    DI --> PO["city (Tx)"]
    DI --> PR["province (Ch)"]
    CO --> NO["name (Tx)"]
    CO --> CE["email (Tx)"]
    PA --> FO["method (Btn)"]
    PA --> IB["iban (Tx)"]

So the postal code is called customer.address.postalCode. Some consequences:

  • form.getField("customer.address.postalCode") finds it; getField("postalCode") returns null (we've checked it): you have to use the full name.
  • field.getPartialName() returns postalCode; field.getFullyQualifiedName() returns customer.address.postalCode.
  • getField("customer") returns the intermediate node, a PDNonTerminalField.
  • Intermediate nodes can define inheritable attributes (/FT, /Ff, /V, /DA…) that apply to their children unless the children redefine them.
  • The hierarchy is useful for organising things (and, as we'll see in 05-02, the XFDF format mirrors it), but it isn't mandatory: many forms have all their fields at the root with names like Customer_VAT_ID.

A word of warning: two widgets with the same full name are, by definition, the same field, and they share a value. That's the correct way to repeat a piece of data (for example, the VAT ID in the header of every page), but it's also a source of bugs if two different fields end up with the same name by accident.

Field types in PDFBox

The type is stored in /FT (field type) and, for buttons and lists, it's refined with flags. PDFBox automatically creates the appropriate subclass:

PDFBox class /FT What it is Value (getValueAsString())
PDTextField Tx Single-line or multiline text, password, comb The text
PDCheckBox Btn Checkbox The on state (here Yes) or Off
PDRadioButton Btn + Radio flag Group of mutually exclusive options The state of the chosen button or Off
PDPushButton Btn + PushButton flag Button that triggers an action (print, submit…) Has no value
PDComboBox Ch + Combo flag Drop-down list (optionally editable) List with the chosen option, e.g. [22]
PDListBox Ch Visible list, single or multiple selection List with the chosen options
PDSignatureField Sig Space for a digital signature The signature, if any (module 7)
PDNonTerminalField (none) Intermediate node in the tree Empty

The class hierarchy helps you write generic code:

classDiagram
    PDField <|-- PDNonTerminalField
    PDField <|-- PDTerminalField
    PDTerminalField <|-- PDButton
    PDTerminalField <|-- PDVariableText
    PDTerminalField <|-- PDSignatureField
    PDButton <|-- PDCheckBox
    PDButton <|-- PDRadioButton
    PDButton <|-- PDPushButton
    PDVariableText <|-- PDTextField
    PDVariableText <|-- PDChoice
    PDChoice <|-- PDComboBox
    PDChoice <|-- PDListBox

PDVariableText groups the fields whose content is text drawn with a font (text fields and lists): they're the ones that use /DA, and the ones whose appearances PDFBox knows how to regenerate. Buttons, by contrast, have their appearances already drawn for each state.

Field flags: ReadOnly, Required and NoExport

/Ff is an integer in which each bit is a flag. The first three are common to all fields:

Bit Value Flag Meaning Methods
1 1 ReadOnly The user can't change it in the viewer isReadOnly() / setReadOnly(boolean)
2 2 Required Must have a value before the form is submitted isRequired() / setRequired(boolean)
3 4 NoExport Not included when the data is submitted/exported isNoExport() / setNoExport(boolean)

The other bits depend on the type: Multiline (4096), Comb (16777216) or Password for text; Radio (32768), PushButton (65536) or NoToggleToOff (16384) for buttons; Combo (131072), Edit or MultiSelect for lists. PDFBox exposes them as named methods (setMultiline, setComb, isRadioButton…), so you'll almost never have to work out bits by hand. Out of curiosity, these are the actual values in our form:

  • customer.taxId: 16777218 = Comb (16777216) + Required (2).
  • payment.method: 32770 = Radio (32768) + Required (2).
  • internal.registrationNumber: 5 = ReadOnly (1) + NoExport (4).

An essential point that we'll verify in the next lesson: these flags are hints for the viewer, not locks. PDFBox can write to a ReadOnly field without any problem, and it doesn't check Required fields: validation is our program's responsibility.

Default resources (/DR), default appearance (/DA) and NeedAppearances

When someone types in a text field, the viewer has to draw that text. To do so it needs to know which font, size and colour to use. That information lives in two places:

  • /DR (Default Resources): a resource dictionary for the form, mainly fonts, with a short name for each one. In our form: /Helv (Helvetica) and /ZaDb (ZapfDingbats, the symbol font for ✓ and ●).
  • /DA (Default Appearance): a string of content operators, on the form and/or on each field. For example:
/Helv 10 Tf 0 g
  │    │  │  │ └─ g: greyscale fill colour
  │    │  │  └─── 0 = black (1 = white)
  │    │  └────── Tf: "set font" operator
  │    └───────── size in points (0 = automatic: fit to the field)
  └────────────── name of the font in /DR

For an RGB colour you use rg: /Helv 10 Tf 0.12 0.23 0.37 rg. The font named in /DA must exist in /DR; otherwise PDFBox throws an exception when generating the appearance.

The third element is the NeedAppearances flag. When it's true, it tells the viewer: "the stored appearances may be out of date; regenerate them yourself from the values". Some tools set it instead of drawing the appearances. It looks convenient, but it has drawbacks we'll study in 05-02 and 05-04: not every viewer honours it (PDFBox's renderer, for example, ignores it), and Acrobat will ask to save changes when the document is closed even if nothing has been modified.

The /DA font decides which characters can be typed. Helvetica, as a standard font, uses WinAnsi encoding (lesson 02-02): Spanish accented letters work, but a name like "Dvořák" doesn't. We'll solve this in 05-02 by adding a Unicode font to /DR.

FormInspector: the inventory of a form

With all of the above we can write the first class in the new com.invoicelab.forms package: a tool that, given a PDF, shows its configuration (XFA, /DA, /DR, NeedAppearances) and a table with one row per widget: full name, type, value, flags, page and rectangle. It's the first thing worth doing with any form that comes from outside, because the field names are the contract we'll use to read it and fill it in.

package com.invoicelab.forms;

import java.io.IOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationWidget;
import org.apache.pdfbox.pdmodel.interactive.form.PDAcroForm;
import org.apache.pdfbox.pdmodel.interactive.form.PDField;
import org.apache.pdfbox.pdmodel.interactive.form.PDNonTerminalField;

/** Inventory of a form: which fields it has, of what type, with what value and where each widget is. */
public final class FormInspector {

    /** One row of the inventory: one widget of a terminal field. */
    public record Entry(String name, String type, String value, String flags, int page, PDRectangle rect) {
    }

    private FormInspector() {
    }

    public static void main(String[] args) throws IOException {
        Path pdf = Path.of(args.length > 0 ? args[0] : "output/registration-form.pdf");
        try (PDDocument document = Loader.loadPDF(pdf.toFile())) {
            print(document);
        }
    }

    public static void print(PDDocument document) throws IOException {
        PDAcroForm form = document.getDocumentCatalog().getAcroForm(null);
        if (form == null) {
            System.out.println("The document has no form.");
            return;
        }
        if (form.hasXFA()) {
            System.out.println("Warning! The form contains"
                    + (form.xfaIsDynamic() ? " DYNAMIC XFA (there are no AcroForm fields to fill in)." : " XFA (static)."));
        }
        System.out.printf("DA=%s  NeedAppearances=%s  DR=%s%n", form.getDefaultAppearance(),
                form.getNeedAppearances(), form.getDefaultResources() == null ? "-"
                        : form.getDefaultResources().getFontNames());
        System.out.printf("%-28s %-12s %-14s %-4s %3s %s%n", "FIELD", "TYPE", "VALUE", "FLAG", "PG", "RECT (x, y, width, height)");
        for (Entry e : inventory(document, form)) {
            PDRectangle r = e.rect();
            System.out.printf("%-28s %-12s %-14s %-4s %3d (%.0f, %.0f, %.0f, %.0f)%n", e.name(), e.type(),
                    truncate(e.value(), 14), e.flags(), e.page(),
                    r.getLowerLeftX(), r.getLowerLeftY(), r.getWidth(), r.getHeight());
        }
    }

    /** Walks the whole tree and returns one entry for each widget of each terminal field. */
    public static List<Entry> inventory(PDDocument document, PDAcroForm form) throws IOException {
        List<Entry> entries = new ArrayList<>();
        for (PDField field : form.getFieldTree()) {               // walks parents and children
            if (field instanceof PDNonTerminalField) {
                continue;                                         // "folders" have no widgets
            }
            for (PDAnnotationWidget widget : field.getWidgets()) {
                entries.add(new Entry(field.getFullyQualifiedName(),
                        field.getClass().getSimpleName().substring(2),   // PDTextField → TextField
                        field.getValueAsString(), flags(field),
                        pageNumber(document, widget), widget.getRectangle()));
            }
        }
        return entries;
    }

    /** R = read-only, Q = reQuired, X = no export. */
    private static String flags(PDField field) {
        return (field.isReadOnly() ? "R" : "") + (field.isRequired() ? "Q" : "") + (field.isNoExport() ? "X" : "");
    }

    /** Page (1-based) of the widget. /P is optional, so if it's missing we search the /Annots of each page. */
    private static int pageNumber(PDDocument document, PDAnnotationWidget widget) throws IOException {
        PDPage page = widget.getPage();
        if (page != null) {
            return document.getPages().indexOf(page) + 1;
        }
        int number = 1;
        for (PDPage p : document.getPages()) {
            for (PDAnnotation annotation : p.getAnnotations()) {
                if (annotation.getCOSObject() == widget.getCOSObject()) {
                    return number;
                }
            }
            number++;
        }
        return 0;                                                   // orphan widget: not on any page
    }

    private static String truncate(String text, int max) {
        String clean = text.replace('\n', ' ');
        return clean.length() <= max ? clean : clean.substring(0, max - 1) + "…";
    }
}

Let's go through the important parts:

  • getAcroForm(null): we read the form without automatic fixups, to see exactly what's in the file.
  • XFA check: if the form is dynamic XFA, the inventory will come out empty, and it's better to warn the user than to leave them puzzled.
  • getFieldTree() walks the whole tree. If we used getFields() we'd only see the roots (customer, contact, payment…), which are intermediate nodes without data.
  • instanceof PDNonTerminalField: we skip intermediate nodes, which have no widgets.
  • One row per widget: that's why payment.method will appear three times, once per button.
  • getClass().getSimpleName().substring(2): strips the PD prefix from the class name for more readable output.
  • pageNumber: according to the standard, the widget's /P key is optional, and many generators don't write it. If it's missing, we look for the widget in each page's /Annots array, comparing the COS dictionaries by identity (==). If it doesn't appear on any page, it's an orphan widget: it exists as a field but isn't visible.
  • truncate: replaces line breaks (multiline fields have them) and shortens long values so the table doesn't get misaligned.

Running it on the blank form gives us:

DA=/Helv 10 Tf 0 g  NeedAppearances=false  DR=[COSName{Helv}, COSName{ZaDb}]
FIELD                        TYPE         VALUE          FLAG  PG RECT (x, y, width, height)
customer.companyName         TextField                   Q      1 (51, 701, 493, 16)
customer.taxId               TextField                   Q      1 (51, 665, 126, 16)
customer.address.street      TextField                   Q      1 (189, 665, 355, 16)
customer.address.postalCode  TextField                   Q      1 (51, 629, 70, 16)
customer.address.city        TextField                   Q      1 (133, 629, 220, 16)
customer.address.province    ComboBox     []             Q      1 (365, 629, 179, 16)
contact.name                 TextField                          1 (51, 573, 300, 16)
contact.phone                TextField                          1 (363, 573, 181, 16)
contact.email                TextField                   Q      1 (51, 537, 300, 16)
payment.method               RadioButton  Off            Q      1 (51, 495, 11, 11)
payment.method               RadioButton  Off            Q      1 (211, 495, 11, 11)
payment.method               RadioButton  Off            Q      1 (371, 495, 11, 11)
payment.iban                 TextField                          1 (51, 461, 300, 16)
notes                        TextField                          1 (51, 387, 493, 44)
terms.accepted               CheckBox     Off            Q      1 (51, 348, 11, 11)
terms.privacy                CheckBox     Off            Q      1 (51, 332, 11, 11)
terms.marketing              CheckBox     Off                   1 (51, 284, 11, 11)
signature.placeDate          TextField                          1 (51, 229, 200, 16)
signature.customer           SignatureField                       1 (281, 195, 263, 50)
internal.registrationNumber  TextField                   RX     1 (57, 156, 150, 12)

What this table tells us:

  • There are 18 fields and 20 widgets (the three radio buttons share a field).
  • Unticked checkboxes and the unselected radio group are worth Off; the empty combo box returns [] because its value is a list.
  • Required fields carry Q; the internal registration number is read-only and not exportable (RX).
  • The rectangles are in points, with the origin at the bottom left (lesson 02-01): the VAT ID box measures 126 × 16 points and sits 665 points above the bottom edge.

Keep these names handy: in the next lesson we'll use them to fill in and read the registration form.

Common Mistakes and Tips

  • Looking up a field by its partial name. getField("taxId") returns null if the field sits inside customer. Always use the fully qualified name and, when in doubt, run FormInspector.
  • Iterating over getFields() thinking those are all the fields. They're only the roots. To walk everything, use getFieldTree().
  • Confusing field and widget. The value is in the field; the position, page and appearance are in the widget. A field can have several widgets.
  • Assuming widget.getPage() is never null. /P is optional. Search /Annots as pageNumber does.
  • Using getAcroForm() to inspect. Its automatic fixups can change the document (generating appearances, turning off NeedAppearances). For analysis, use getAcroForm(null).
  • Trying to fill in dynamic XFA. It has no AcroForm fields: check xfaIsDynamic() before wasting your time.
  • Trusting the flags. ReadOnly and Required are hints for the viewer. The real validation will be done by your code (05-02).
  • Tip: when you receive a form from a third party, store the inventory output alongside the code that processes it. If the sender publishes a new version with renamed fields, comparing inventories will tell you in seconds what has changed.

Exercises

Exercise 1. Write a method printTree(List<PDField> fields, int level) that shows the field tree with indentation (two spaces per level) and, for terminal fields, their /FT type in parentheses. Call it with form.getFields(). Hint: recursion with PDNonTerminalField.getChildren() and PDField.getFieldType().

Exercise 2. The value of a radio group is the name of the on state of the chosen button. Write a method Set<String> onStates(PDAnnotationWidget widget) that reads the keys of a widget's normal appearance subdictionary (/AP /N) and returns all of them except Off. Use it to list, for each checkbox and each radio button in the registration form, the value it would take when selected.

Exercise 3. Write FormType classify(Path pdf), where FormType is an enum with NO_FORM, ACROFORM, XFA_HYBRID and XFA_DYNAMIC. Test it with registration-form.pdf and with an InvoiceLab invoice.

Solutions

Solution 1.

static void printTree(List<PDField> fields, int level) {
    for (PDField field : fields) {
        String type = field instanceof PDNonTerminalField ? "" : "  (" + field.getFieldType() + ")";
        System.out.println("  ".repeat(level) + field.getPartialName() + type);
        if (field instanceof PDNonTerminalField parent) {
            printTree(parent.getChildren(), level + 1);             // go down one level
        }
    }
}

instanceof with a pattern variable (PDNonTerminalField parent) avoids the explicit cast (Java 16+). The output starts like this:

customer
  companyName  (Tx)
  taxId  (Tx)
  address
    street  (Tx)
    postalCode  (Tx)
    city  (Tx)
    province  (Ch)
contact
  name  (Tx)
...

Notice that getFieldType() returns the value of /FT: Tx, Btn, Ch or Sig. That's why checkboxes and radio buttons both show up as Btn.

Solution 2.

static Set<String> onStates(PDAnnotationWidget widget) {
    Set<String> states = new TreeSet<>();
    if (widget.getAppearance() == null) {
        return states;                                    // widget without appearances
    }
    PDAppearanceEntry normal = widget.getAppearance().getNormalAppearance();   // /AP /N
    if (normal != null && normal.isSubDictionary()) {    // buttons: one stream per state
        for (COSName name : normal.getSubDictionary().keySet()) {
            if (!name.equals(COSName.Off)) {              // Off, not OFF!
                states.add(name.getName());
            }
        }
    }
    return states;
}

And to iterate over the buttons:

for (PDField field : form.getFieldTree()) {
    if (field instanceof PDButton button && !button.isPushButton()) {
        for (PDAnnotationWidget w : button.getWidgets()) {
            System.out.println(field.getFullyQualifiedName() + " → " + onStates(w));
        }
    }
}

Result: payment.method → [Transfer], [DirectDebit] and [PromissoryNote] (one per widget) and [Yes] for each checkbox. Watch out for the constant trap: PDFBox has both COSName.Off (/Off, the button state) and COSName.OFF (/OFF, used in optional content). They're different names: PDF is case-sensitive. Notice too that text field widgets have /AP /N as a direct stream, not as a subdictionary: that's why we check isSubDictionary().

Solution 3.

enum FormType { NO_FORM, ACROFORM, XFA_HYBRID, XFA_DYNAMIC }

static FormType classify(Path pdf) throws IOException {
    try (PDDocument document = Loader.loadPDF(pdf.toFile())) {
        PDAcroForm form = document.getDocumentCatalog().getAcroForm(null);
        if (form == null) {
            return FormType.NO_FORM;
        }
        if (form.xfaIsDynamic()) {                        // XFA without AcroForm fields
            return FormType.XFA_DYNAMIC;
        }
        return form.hasXFA() ? FormType.XFA_HYBRID : FormType.ACROFORM;
    }
}

The order of the checks matters: xfaIsDynamic() already implies hasXFA(), so it's evaluated first. With registration-form.pdf it returns ACROFORM, and with F-2026-0001.pdf, NO_FORM. A sensible improvement would be to also distinguish an /AcroForm that's present but has no fields (some generators leave it empty, and a form flattened with PDFBox ends up like that, as we'll see in 05-04).

Conclusion

You now know how an AcroForm form is built: an /AcroForm dictionary in the catalog with the root fields, the shared configuration (/DR, /DA, NeedAppearances) and a field tree whose fully qualified names (customer.address.postalCode) are the way to locate them. You can tell the field, which stores the name, type, value and flags, from the widget, the annotation you see on the page; you know the PDFBox classes for each field type, and you can detect the XFA forms that PDFBox can't fill in. With FormInspector you also have a tool for learning the contract of any form before touching it.

In the next lesson we'll put this into action: we'll use those names to read and fill in the registration form. We'll see how to assign a value to each field type, how to turn a received registration into an InvoiceLab Customer while validating its data, what to do when the form's font doesn't support a character, and how to generate a hundred prefilled forms in one go.

PDF Generation and Editing with Apache PDFBox

Module 1: PDF and PDFBox Fundamentals

Module 2: Generating Content

Module 3: Business Documents

Module 4: Editing Existing PDFs

Module 5: AcroForm Forms

Module 6: Extraction and Analysis

Module 7: Security and Digital Signatures

Module 8: PDFBox in Production

© Copyright 2026. All rights reserved