Open invoice F-2026-0001 with a screen reader and what you'll hear is something like alphabet soup: the invoice number jumbled up with the customer's address, the amounts in the table read out with no idea which column they belong to, "Page 1 of 2" in the middle of the text and not a word about the logo. To a program, our pages are just glyphs placed at coordinates; nothing says what's a heading, what's a table or what's decoration. A tagged PDF adds that information: a logical structure, running parallel to the drawing, that describes the document the way well-written HTML would. In this lesson we'll build the Tagger utility, use it to generate a simplified, accessible version of the invoice that passes veraPDF's PDF/UA-1 validation, and see how to integrate it into InvoiceLab's block architecture.

Contents

  1. What a tagged PDF is and what PDF/UA is
  2. The pieces of a tagged PDF
  3. Standard structure types
  4. Marked content and MCIDs
  5. The parent tree (/ParentTree)
  6. The Tagger utility
  7. Tagging a simplified invoice
  8. Accessible links
  9. Validating: veraPDF and PAC
  10. Integrating it into the block architecture
  11. PDFBox limitations

What a tagged PDF is and what PDF/UA is

A tagged PDF (ISO 32000, section 14.8) contains, in addition to the pages, a structure tree whose nodes are elements such as "level 1 heading", "paragraph", "table" or "figure", and whose leaves point to the specific pieces of page content that belong to them. Assistive technologies (screen readers such as NVDA or JAWS, braille displays, viewers' reading modes) walk through that tree instead of the drawing.

PDF/UA (Universal Accessibility, ISO 14289-1) is the standard that defines when a tagged PDF is accessible. Some of its requirements:

  • All real content is tagged and everything decorative is marked as an artifact.
  • The logical order of the tree is the reading order.
  • Meaningful images carry alternative text.
  • Headings follow a hierarchy without gaps (H1, H2, H3...).
  • Tables have identifiable header cells.
  • The document declares its language and its title, and the viewer displays the title.
  • The text has a Unicode mapping (fonts with /ToUnicode).
  • Annotations (links) are tagged and have a description.
Standard What it guarantees Relationship
Tagged PDF (ISO 32000) That there is a structure Technical mechanism
PDF/UA-1 (ISO 14289-1) That the structure is accessible Builds on tagged PDF
PDF/A-1a, 2a, 3a Archiving + tagged structure Less demanding than PDF/UA
WCAG 2.x Accessibility of web content (and documents published on the web) Refers to PDF techniques

In many countries, making the documents a company or public body publishes accessible is a legal obligation; check the regulations that apply to your case. For Nebula Distribution it's also simply a matter of making sure all its customers can read their invoices.

The pieces of a tagged PDF

flowchart TB
    CAT["Catalog<br/>/MarkInfo: Marked true<br/>/Lang (en-GB)<br/>/ViewerPreferences: DisplayDocTitle true"]
    CAT --> STR["/StructTreeRoot"]
    STR --> DOC["/Document"]
    STR --> PT["/ParentTree<br/>(number tree)"]
    DOC --> FIG["/Figure<br/>/Alt (Logo...)"]
    DOC --> H1["/H1"]
    DOC --> TAB["/Table"]
    TAB --> TR["/TR"]
    TR --> TH["/TH"]
    TR --> TD["/TD"]
    H1 -. "MCID 1" .-> PAG["Page 1: content stream<br/>/H1 (MCID 1) BDC ... EMC"]
    PAG -. "/StructParents 0" .-> PT
    PT -. "0 → [Figure, H1, ...]" .-> H1
Piece Where it lives What it's for PDFBox class
Structure tree The catalog's /StructTreeRoot Logical hierarchy PDStructureTreeRoot, PDStructureElement
Marked content Content stream: BDC ... EMC Delimits which drawing belongs to which element beginMarkedContent, PDPropertyList
MCID The /MCID property of each BDC Number linking drawing and element COSName.MCID
Parent tree /ParentTree Reverse path: from drawing to element PDNumberTreeNode, PDParentTreeValue
/MarkInfo Catalog Declares that the PDF is tagged PDMarkInfo
/Lang Catalog (and elements) Language for the reader's voice setLanguage
DisplayDocTitle Viewer preferences Announce the title, not the file name PDViewerPreferences
Artifacts /Artifact BDC ... EMC Content the reader should ignore COSName.ARTIFACT

Remember that Metadata.forInvoice (04-06) already sets /Lang and DisplayDocTitle: we prepared them back then precisely for this lesson.

Standard structure types

StandardStructureTypes defines the standard's types as constants. The ones we'll use:

Type Constant Use in the invoice
Document DOCUMENT Root of all the content
H1, H2 H1, H2 "Invoice F-2026-0001"; "Issuer", "Customer"
P P Date, address lines, totals
Figure Figure Nebula's logo (with /Alt)
Table, THead, TBody TABLE, T_HEAD, T_BODY Table of lines
TR, TH, TD TR, TH, TD Rows, headers and cells
Link LINK Verification link
L, LI, Lbl, LBody L, LI... Lists (we don't use them here)

You can define your own types (for example Amount) if you map them to a standard one through the root's /RoleMap (setRoleMap). To begin with, stick to the standard ones.

Marked content and MCIDs

In the content stream, each piece of real content is enclosed between BDC (begin marked content with properties) and EMC, with the element's tag and an MCID (marked-content identifier) that is unique within the page:

/H1 <</MCID 1>> BDC
  BT /F1 18 Tf 412.6 771.9 Td (Invoice F-2026-0001) Tj ET
EMC
/Artifact <</Type /Pagination>> BDC
  BT /F2 7.5 Tf ... (Page 1 of 1) Tj ET
EMC

In PDFBox it's written like this:

COSDictionary properties = new COSDictionary();
properties.setInt(COSName.MCID, 1);
content.beginMarkedContent(COSName.getPDFName("H1"), PDPropertyList.create(properties));
// ... beginText, showText, endText ...
content.endMarkedContent();
  • PDPropertyList.create(COSDictionary) wraps the properties dictionary; PDFBox writes it inline in the BDC operator.
  • Recent 3.0.x versions (checked in 3.0.8) include the shortcut beginMarkedContent(COSName tag, int mcid), which writes exactly the same thing. We use the dictionary form because it works across the whole 3.0 branch and lets you add other properties.
  • Marked content can contain anything: text, images, paths. What matters is that all of the page content is inside a tagged sequence or an artifact.
  • Sequences must be closed in the same content stream in which they were opened, and must not leave a BT open in between.

The parent tree (/ParentTree)

An element knows which MCIDs belong to it (it stores them in its /K), but tools also need the reverse path: "I'm reading MCID 7 on page 1; which element does it belong to?". That's what the parent tree is for: a number tree (PDNumberTreeNode) in which:

  • Each page has its own key, stored in its /StructParents.
  • The value for that key is an array in which position n holds the element that owns MCID n.
  • Each tagged annotation also has a key (/StructParent, singular) whose value is its element directly.
  • /ParentTreeNextKey gives the first free key.
Key Used by Value
0 Page 1 (/StructParents 0) [Figure, H1, P, H2, P, ...] (63 elements)
1 Verification link (/StructParent 1) The Link element

Building it by hand is tedious and error-prone, which is why Tagger will do it automatically.

The Tagger utility

Tagger lives in the new com.invoicelab.accessibility package and accompanies one document while it's being drawn, like InvoiceLabFonts or PdfContext. The constructor prepares the catalog:

public final class Tagger {

    @FunctionalInterface
    public interface Drawing {
        void draw() throws IOException;
    }

    private final PDStructureTreeRoot root;
    private final PDStructureElement document;
    /** Per page: the structure element of each MCID (the position in the list IS the MCID). */
    private final Map<PDPage, List<PDStructureElement>> mcidsByPage = new LinkedHashMap<>();
    /** Tagged annotations (links): their /StructParent points directly to an element. */
    private final Map<PDAnnotation, PDStructureElement> annotations = new LinkedHashMap<>();

    public Tagger(PDDocument doc, String language) {
        PDDocumentCatalog catalog = doc.getDocumentCatalog();
        root = new PDStructureTreeRoot();
        catalog.setStructureTreeRoot(root);

        PDMarkInfo markInfo = new PDMarkInfo();
        markInfo.setMarked(true);                         // "this PDF is tagged"
        catalog.setMarkInfo(markInfo);
        catalog.setLanguage(language);                    // default language of the text

        PDViewerPreferences preferences = catalog.getViewerPreferences();
        if (preferences == null) {
            preferences = new PDViewerPreferences(new COSDictionary());
            catalog.setViewerPreferences(preferences);
        }
        preferences.setDisplayDocTitle(true);             // the viewer announces the title, not the file

        document = new PDStructureElement(StandardStructureTypes.DOCUMENT, root);
        root.appendKid(document);
    }
  • Drawing is a functional interface that can throw IOException, like the ones in Stamper (04-02): that way we can pass lambdas that call showText.
  • The mcidsByPage map is the key piece: for each page it keeps a list in which the position is the MCID. With it we assign consecutive MCIDs and, at the end, build the parent tree effortlessly.

Creating elements is simple; we add two shortcuts for the cases with requirements of their own:

    public PDStructureElement document() {
        return document;
    }

    /** Creates a child element of a standard type (H1, P, Table, TR, TD...). */
    public PDStructureElement element(PDStructureElement parent, String type) {
        PDStructureElement child = new PDStructureElement(type, parent); // sets /P (parent) on the child
        parent.appendKid(child);                                         // and adds it to the parent's /K
        return child;
    }

    /** A figure with its alternative text (what the screen reader will read out). */
    public PDStructureElement figure(PDStructureElement parent, String alternativeText) {
        PDStructureElement figure = element(parent, StandardStructureTypes.Figure);
        figure.setAlternateDescription(alternativeText);
        return figure;
    }

    /** Column header cell: /TH with the /Scope /Column attribute. */
    public PDStructureElement columnHeader(PDStructureElement row) {
        PDStructureElement th = element(row, StandardStructureTypes.TH);
        PDTableAttributeObject attributes = new PDTableAttributeObject();
        attributes.setScope(PDTableAttributeObject.SCOPE_COLUMN);
        th.addAttribute(attributes);
        return th;
    }

The central method, mark, opens the sequence, draws, closes it and records the MCID in both directions:

    public void mark(PDPageContentStream content, PDPage page, PDStructureElement element, Drawing drawing)
            throws IOException {
        List<PDStructureElement> onPage = mcidsByPage.computeIfAbsent(page, p -> new ArrayList<>());
        int mcid = onPage.size();                         // 0, 1, 2... within each page
        onPage.add(element);                              // drawing → element (for the ParentTree)

        COSDictionary properties = new COSDictionary();
        properties.setInt(COSName.MCID, mcid);
        content.beginMarkedContent(COSName.getPDFName(element.getStructureType()),
                PDPropertyList.create(properties));
        drawing.draw();
        content.endMarkedContent();

        if (element.getPage() == null) {
            element.setPage(page);                        // /Pg: default page for its MCIDs
        }
        if (element.getPage().getCOSObject() == page.getCOSObject()) {
            element.appendKid(mcid);                      // element → drawing: "short" MCID
        } else {
            PDMarkedContentReference reference = new PDMarkedContentReference();
            reference.setPage(page);                      // the element continues on another page
            reference.setMCID(mcid);
            element.appendKid(reference);
        }
    }
  • An element can have content on several pages (a table that continues). The first MCID sets its /Pg; those on other pages are added as PDMarkedContentReference (/MCR), which carries its own page.
  • We compare getCOSObject() with == because two different PDPage objects can wrap the same dictionary.

Artifacts are marked with /Artifact and no MCID, because they don't belong to any element:

    public void artifact(PDPageContentStream content, Drawing drawing) throws IOException {
        COSDictionary properties = new COSDictionary();
        properties.setName(COSName.TYPE, "Pagination");    // also Layout, Page or Background
        content.beginMarkedContent(COSName.ARTIFACT, PDPropertyList.create(properties));
        drawing.draw();
        content.endMarkedContent();
    }

Finally, finish builds the parent tree. It's called once, after all the pages have been drawn and before saving:

    public void finish() {
        Map<Integer, COSObjectable> parents = new HashMap<>();
        int key = 0;
        for (Map.Entry<PDPage, List<PDStructureElement>> e : mcidsByPage.entrySet()) {
            COSArray elements = new COSArray();
            for (PDStructureElement element : e.getValue()) {
                elements.add(element);                    // position n = element of MCID n
            }
            e.getKey().setStructParents(key);
            parents.put(key, new PDParentTreeValue(elements));
            key++;
        }
        for (Map.Entry<PDAnnotation, PDStructureElement> e : annotations.entrySet()) {
            e.getKey().setStructParent(key);              // the annotation points to its element
            parents.put(key, e.getValue());
            key++;
        }
        PDNumberTreeNode tree = new PDNumberTreeNode(PDParentTreeValue.class);
        tree.setNumbers(parents);
        root.setParentTree(tree);
        root.setParentTreeNextKey(key);
        for (PDPage page : mcidsByPage.keySet()) {
            page.getCOSObject().setName(COSName.getPDFName("Tabs"), "S");    // tab order follows the structure
        }
    }
  • PDParentTreeValue wraps the array (or the dictionary, in the case of annotations) so that the number tree accepts it as a COSObjectable.
  • /Tabs /S makes the Tab key move through the annotations in structure order. In 05-03 we saw /R and /C; PDF/UA requires /S on every page with annotations.

One detail remains: declaring in the XMP that the document claims to comply with PDF/UA-1. The static method Tagger.declarePdfUa(doc) does this: it reads the XMP with Metadata.readXmp, uses createAndAddDefaultSchema("pdfuaid", "http://www.aiim.org/pdfua/ns/id/") to add the integer property part = 1, and saves it again, just as we did with pdfaid in 08-01. It must be called after Metadata.forInvoice, which regenerates the XMP.

Tagging a simplified invoice

Rewriting the whole of InvoiceGenerator with tags is more than one lesson can cover, so the AccessibleInvoice example draws a one-page version with 8 lines: logo, title, date, issuer, customer, table, totals, link and footer. What matters isn't the layout, which you've already mastered, but that every drawing operation goes through mark or artifact:

Tagger tg = new Tagger(doc, "en-GB");
PDStructureElement root = tg.document();
float height = page.getMediaBox().getHeight();

try (PDPageContentStream cs = new PDPageContentStream(doc, page)) {
    // Decorative top band: artifact
    tg.artifact(cs, () -> {
        cs.setNonStrokingColor(NebulaColors.BLUE);
        cs.addRect(0, height - Measures.mm(6), page.getMediaBox().getWidth(), Measures.mm(6));
        cs.fill();
    });
    // Logo: figure with alternative text
    PDStructureElement figure = tg.figure(root, "Nebula Distribution logo");
    tg.mark(cs, page, figure, () -> Images.drawFitted(cs, logo, 57, height - 40, 150, 50));

    // Title and date
    PDStructureElement h1 = tg.element(root, StandardStructureTypes.H1);
    tg.mark(cs, page, h1, () -> text(cs, bold, 18, "Invoice " + f.number(), 538, height - 70,
            Alignment.RIGHT));
    PDStructureElement date = tg.element(root, StandardStructureTypes.P);
    tg.mark(cs, page, date, () -> text(cs, regular, 10, "Date: " + Formats.date(f.date()),
            538, height - 88, Alignment.RIGHT));
    // ...

text(...) is a small helper method that sanitises the text with InvoiceLabFonts.sanitize and calls TextMetrics.writeAligned (02-04). Pay attention to the order: the order in which the elements are created is the reading order, even though the title is drawn to the right of and lower than the logo.

The table of lines

The table is where the difference is most noticeable. Structure: Table → THead → TR → TH (with /Scope /Column) and TBody → TR → TD. Backgrounds and rules are artifacts:

PDStructureElement table = tg.element(root, StandardStructureTypes.TABLE);
PDStructureElement headerRow = tg.element(tg.element(table, StandardStructureTypes.T_HEAD),
        StandardStructureTypes.TR);
float yHeader = y;
tg.artifact(cs, () -> {                                      // blue header background
    cs.setNonStrokingColor(NebulaColors.BLUE);
    cs.addRect(COLUMN_X[0], yHeader - 5, COLUMN_X[5] - COLUMN_X[0], 17);
    cs.fill();
});
for (int c = 0; c < HEADERS.length; c++) {
    int col = c;                                             // effectively final copy for the lambda
    PDStructureElement th = tg.columnHeader(headerRow);
    tg.mark(cs, page, th, () -> {
        cs.setNonStrokingColor(Color.WHITE);
        cell(cs, bold, HEADERS[col], col, yHeader);
    });
}
PDStructureElement body = tg.element(table, StandardStructureTypes.T_BODY);
y -= 18;
for (InvoiceLine l : f.lines()) {
    String[] values = { l.reference(),
            TextMetrics.truncateWithEllipsis(regular, 8.5f, l.description(), COLUMN_X[2] - COLUMN_X[1] - 8),
            Formats.quantity(l.quantity()), Formats.price(l.unitPrice()), Formats.euros(l.amount()) };
    PDStructureElement row = tg.element(body, StandardStructureTypes.TR);
    float yRow = y;
    for (int c = 0; c < values.length; c++) {
        int col = c;
        PDStructureElement td = tg.element(row, StandardStructureTypes.TD);
        tg.mark(cs, page, td, () -> {
            cs.setNonStrokingColor(Color.BLACK);
            cell(cs, regular, values[col], col, yRow);
        });
    }
    tg.artifact(cs, () -> Shapes.horizontalLine(cs, COLUMN_X[0], COLUMN_X[5], yRow - 5,
            0.5f, NebulaColors.LINE_GREY));                  // rule between rows
    y -= 16;
}
  • COLUMN_X holds the edges of the 5 columns (Ref., Description, Qty, Price, Amount) and cell aligns each value within its column.
  • Variables used inside the lambdas (col, yRow, yHeader) must be effectively final, which is why they're copied first. It's the most common compilation error when writing this kind of code.
  • With the header tagged as TH and /Scope /Column, the reader announces "Amount, 18,40 €" instead of a bare "18,40 €".

The totals are three paragraphs (P) and the "Page 1 of 1" footer is a pagination artifact. When we're done:

}                                                            // closes the content stream
tg.finish();                                                 // ParentTree, StructParents, /Tabs
Metadata.forInvoice(doc, f, ZonedDateTime.now(ZoneId.of("Europe/Madrid")));   // Info, XMP, /Lang
Tagger.declarePdfUa(doc);                                    // pdfuaid:part = 1
doc.save(target.toFile());

The result, output/accessible/F-2026-0001-accessible.pdf, is 45,129 bytes. This is its structure tree (printed by the solution to exercise 2):

Document
  Figure [Alt: Nebula Distribution logo] (1 MCID)
  H1 (1 MCID)
  P (1 MCID)
  H2 (1 MCID)
  P (1 MCID)          ← 5 paragraphs with the issuer's details
  ...
  H2 (1 MCID)
  P (1 MCID)          ← 4 paragraphs with the customer's details
  ...
  Table
    THead
      TR
        TH (1 MCID)   ← × 5
    TBody
      TR
        TD (1 MCID)   ← × 5, and so on for 8 rows
  P (1 MCID)          ← base, VAT and total
  P
    Link (1 MCID)

Real Unicode

A screen reader doesn't read glyphs: it reads the Unicode characters PDFBox associates with each glyph through the font's /ToUnicode. The PDType0Font fonts loaded by InvoiceLabFonts generate it automatically, so "Tomáš Dvořák" is read as "Tomáš Dvořák". With fonts that lack /ToUnicode (we saw a case in 06-01, with empty extraction and No Unicode mapping warnings), the document can't be accessible, however well it's tagged.

A tip about descriptions truncated with "…": the reader will also read out the truncated text. If the truncation hides important information, you can give the TD the full text with setActualText(...), which replaces the content when it's read out.

Accessible links

In 06-05 we added links to the batch and said that setContents improved accessibility. In PDF/UA a link needs three things: a Link element in the structure containing the visible text, an object reference (/OBJR) from that element to the annotation, and a description in /Contents:

PDStructureElement paragraph = tg.element(root, StandardStructureTypes.P);
PDStructureElement linkElement = tg.element(paragraph, StandardStructureTypes.LINK);
tg.mark(cs, page, linkElement, () -> {
    cs.setNonStrokingColor(NebulaColors.BLUE);
    text(cs, regular, 9.5f, linkLabel, 57, yLink, Alignment.LEFT);
});
PDAnnotationLink link = new PDAnnotationLink();
link.setRectangle(new PDRectangle(57, yLink - 3, TextMetrics.width(regular, 9.5f, linkLabel), 14));
PDActionURI action = new PDActionURI();
action.setURI("https://verifica.example/f?num=" + f.number());
link.setAction(action);
link.setContents("Verify invoice " + f.number() + " with the verification service");
link.setPrinted(true);
page.getAnnotations().add(link);
tg.annotation(linkElement, page, link);

And the Tagger method that ties it together:

    public void annotation(PDStructureElement element, PDPage page, PDAnnotation annotation) {
        PDObjectReference reference = new PDObjectReference();
        reference.setReferencedObject(annotation);              // /OBJR → the annotation
        reference.getCOSObject().setItem(COSName.PG, page);
        element.appendKid(reference);
        if (element.getPage() == null) {
            element.setPage(page);
        }
        annotations.put(annotation, element);                   // its /StructParent is assigned in finish()
    }

Validating: veraPDF and PAC

An incomplete structure is almost worse than none, because the reader trusts it. You have to validate:

  • veraPDF validates PDF/UA-1 (as well as PDF/A). With the library from 08-01 you just ask for the profile: PdfAValidator.veraPdf(pdf, PDFAFlavour.PDFUA_1), an overload that creates the parser and the validator with Foundries.defaultInstance().createParser(input, flavour) and createValidator(flavour, false). From the command line: verapdf --flavour ua1 invoice.pdf.
  • PAC (PDF Accessibility Checker, from the Swiss foundation "Zugang für alle") is the most widely used free tool for checking PDF/UA and WCAG; it includes a preview of how a screen reader will read the document. It's a Windows desktop application.
  • No automatic tool checks that the alternative text makes sense or that the order is logical. Listen to the document with a real screen reader (NVDA is free) at least once per template.

Our results:

output/accessible/F-2026-0001-accessible.pdf  veraPDF ua1: VALID
output/F-2026-0001.pdf                        veraPDF ua1: NOT VALID
   - 6.2-1  The document catalog dictionary shall include a MarkInfo dictionary ... Marked ... true
   - 7.1-11 The logical structure of the conforming file shall be described by a structure hierarchy...
   - 7.1-3  Content shall be marked as Artifact or tagged as real content
   - 7.1-10 ... ViewerPreferences dictionary containing a DisplayDocTitle key ...
   - 7.1-8  The Catalog dictionary of a conforming file shall contain the Metadata key ...
   - 7.2-34 Natural language for text in page content shall be determined

To understand what each rule protects, we deliberately broke the accessible invoice, one change at a time:

Change veraPDF rule that fails
Remove the logo's /Alt 7.3-1 Figure tags shall include an alternative representation...
Remove the link's /Contents 7.18.5-2 Links shall contain an alternate description via their Contents key
Remove /Lang from the catalog 7.2-34 Natural language for text in page content shall be determined (and several more)
Remove /Scope from the THs 7.5-1 If the table's structure is not determinable via Headers and IDs, then ... TH shall have a Scope attribute
Remove the /ParentTree 7.1-3 Content shall be marked as Artifact or tagged... and 7.18.5-1 Links shall be tagged...
Remove /Tabs from the page 7.18.3-1 Every page on which there is an annotation shall contain ... Tabs ... S
Add text without mark 7.1-3 Content shall be marked as Artifact or tagged as real content
Change the H2s to H3 7.4.2-1 ... shall not skip an intervening heading level

Integrating it into the block architecture

How can we bring this to InvoiceGenerator without rewriting it? The architecture from 03-04 helps, because all the drawing goes through a handful of points:

Point in the architecture What it tags How
BaseGenerator.generate Creates the Tagger, calls finish() before save One more field in PdfContext
Paginator.PageHeader Page headers First page: H1 and P; following pages (compact header): artifact
PageFooter.numberPages "Page X of N" footers Artifact (the second pass opens its own stream)
ParagraphBlock, TotalsBlock... Paragraphs and totals TaggedBlock decorator
Table / TableBlock Table, rows and cells Internal change: mark each cell and turn the rules into artifacts
QrBlock QR code Figure with an /Alt explaining the verification URL

For the "simple" blocks, a decorator that leaves the original block untouched is enough:

public final class TaggedBlock implements Block {

    private final Tagger tagger;
    private final String type;
    private final Block inner;

    public TaggedBlock(Tagger tagger, String type, Block inner) {
        this.tagger = tagger;
        this.type = type;
        this.inner = inner;
    }

    @Override
    public float height(PdfContext ctx, float width) throws IOException {
        return inner.height(ctx, width);                    // tagging doesn't change the layout
    }

    @Override
    public float draw(PdfContext ctx, float x, float yTop, float width) throws IOException {
        PDStructureElement element = tagger.element(tagger.document(), type);
        float[] consumed = new float[1];                    // the lambda can't assign local variables
        tagger.mark(ctx.content(), ctx.paginator().page(), element,
                () -> consumed[0] = inner.draw(ctx, x, yTop, width));
        return consumed[0];
    }
}

Usage: ctx.place(new TaggedBlock(tg, StandardStructureTypes.P, new ParagraphBlock("PAYMENT TERMS", text))). Two warnings:

  • If the inner block draws decoration (a box, a rule), it will be tagged as part of the paragraph. PDF/UA doesn't allow artifacts nested inside tagged content, so those blocks need to be tagged from the inside, as we did with the table.
  • ParagraphBlock draws a label and some text: ideally that would be an H2 and a P. The decorator is a quick first step; the fine-grained version is done inside each block.

PDFBox limitations

  • Everything is manual. PDFBox provides the model classes (PDStructureElement, PDMarkedContentReference...), but no layer that automatically tags what you draw, or that reorganises or repairs the structure of an existing PDF.
  • Tagging an already generated untagged PDF is, in practice, not feasible with PDFBox: you'd have to rewrite the content streams. Tag at generation time.
  • Modifying a tagged PDF (stamps from 04-02, pages added in 04-03) can break the structure: anything added must be marked as an artifact or tagged, and when merging documents (04-04) the structure trees have to be merged (PDFMergerUtility tries, but check the result with veraPDF).
  • PDFTextStripper doesn't use the structure: it extracts by position, as we saw in 06-01. To read in logical order you'd have to walk the tree and the marked content yourself.
  • Forms need their own tagging (Form with an /OBJR to each widget) and a descriptive TU on each field.

Common Mistakes and Tips

  • Leaving content unmarked. A single rule outside mark/artifact makes PDF/UA fail (7.1-3). Wrap all the drawing.
  • Forgetting finish() or calling it before you've finished drawing. Without a parent tree, the MCIDs can't be resolved.
  • Reusing MCIDs on the same page or repeating them across a page's content streams. Tagger numbers them per page to avoid this.
  • Useless alternative text ("image", "logo.png"). Describe the purpose: "Nebula Distribution logo". If the image is pure decoration, mark it as an artifact, not as a figure.
  • Skipping heading levels or using H1 for everything. The hierarchy is the reader's table of contents.
  • Calling Metadata.forInvoice after declarePdfUa: it regenerates the XMP and wipes out pdfuaid. Metadata first, then the declaration.
  • Denying the accessibility permission when encrypting (07-01). An encrypted PDF/UA must let assistive technologies read the content.
  • Tip: if you also need PDF/A, level a (PDF/A-2a) requires the same structure; the accessible invoice converted to 2a with PdfAConverter passes veraPDF validation (exercise 1).

Exercises

Exercise 1. Add PDF_A_2A(2, "A") to PdfALevel and convert F-2026-0001-accessible.pdf to PDF/A-2a with PdfAConverter. Validate it with veraPDF. Do the same with the normal invoice F-2026-0001.pdf and compare.

Exercise 2. Write printStructure(PDStructureNode node, String indent) that recursively walks the structure tree and prints each element's type, its /Alt and its /Lang if it has them, and how many direct MCIDs it contains.

Exercise 3. Generate a one-page PDF with the title "Payment terms" (H1) and two paragraphs: one in English and another in Catalan ("Pagament per transferència a 30 dies."). The document is in en-GB, but the reader must read the second paragraph with a Catalan voice. Validate it as PDF/UA-1.

Solutions

Solution 1.

try (PDDocument d = Loader.loadPDF(new File("output/accessible/F-2026-0001-accessible.pdf"))) {
    PdfAConverter.apply(d, PdfALevel.PDF_A_2A);
    Files.write(Path.of("output/accessible/F-2026-0001-pdf-a-2a.pdf"), PdfAConverter.save(d, PdfALevel.PDF_A_2A));
}
System.out.println(PdfAValidator.veraPdf(Path.of("output/accessible/F-2026-0001-pdf-a-2a.pdf")));
accessible → veraPDF 2a: VALID
normal     → veraPDF 2a: NOT VALID
   - 6.7.2.2-1 The document catalog dictionary shall include a MarkInfo dictionary ... Marked ... true
   - 6.7.3.3-1 The logical structure of the conforming file shall be described by a structure hierarchy...

Since the enum keeps the differences in one place, adding the level takes one line. PdfAConverter.apply regenerates the XMP from Info, so the result declares pdfaid but no longer pdfuaid: if you want both, add pdfuaid with its extension schema (PDF/A doesn't recognise it as a predefined schema), just as we did with il: in 08-01.

Solution 2.

static void printStructure(PDStructureNode node, String indent) {
    for (Object child : node.getKids()) {
        if (child instanceof PDStructureElement e) {
            StringBuilder line = new StringBuilder(indent).append(e.getStructureType());
            if (e.getAlternateDescription() != null) {
                line.append(" [Alt: ").append(e.getAlternateDescription()).append("]");
            }
            if (e.getLanguage() != null) {
                line.append(" [Lang: ").append(e.getLanguage()).append("]");
            }
            long mcids = e.getKids().stream().filter(k -> k instanceof Integer).count();
            if (mcids > 0) {
                line.append(" (").append(mcids).append(" MCID)");
            }
            System.out.println(line);
            printStructure(e, indent + "  ");
        }
    }
}
// printStructure(document.getDocumentCatalog().getStructureTreeRoot(), "");

getKids() returns a heterogeneous list: PDStructureElement for child elements, Integer for MCIDs on the default page, and PDMarkedContentReference and PDObjectReference for the rest. That's why we filter with instanceof. The output for the accessible invoice is the tree shown in the lesson.

Solution 3.

try (PDDocument doc = new PDDocument()) {
    PDPage p = new PDPage(PDRectangle.A4);
    doc.addPage(p);
    PDFont f = new InvoiceLabFonts(doc).regular();
    Tagger tg = new Tagger(doc, "en-GB");
    try (PDPageContentStream cs = new PDPageContentStream(doc, p)) {
        PDStructureElement h1 = tg.element(tg.document(), StandardStructureTypes.H1);
        tg.mark(cs, p, h1, () -> TextMetrics.writeAligned(cs, f, 16, "Payment terms",
                57, 780, Alignment.LEFT));
        PDStructureElement en = tg.element(tg.document(), StandardStructureTypes.P);
        tg.mark(cs, p, en, () -> TextMetrics.writeAligned(cs, f, 10,
                "Payment by bank transfer within 30 days.", 57, 750, Alignment.LEFT));
        PDStructureElement ca = tg.element(tg.document(), StandardStructureTypes.P);
        ca.setLanguage("ca-ES");                       // this element's own language
        tg.mark(cs, p, ca, () -> TextMetrics.writeAligned(cs, f, 10,
                "Pagament per transferència a 30 dies.", 57, 735, Alignment.LEFT));
    }
    tg.finish();
    doc.getDocumentInformation().setTitle("Payment terms");
    Metadata.syncXmp(doc);                             // PDF/UA requires dc:title in the XMP
    Tagger.declarePdfUa(doc);
    doc.save("output/accessible/bilingual.pdf");
}
// veraPDF ua1: VALID

An element's /Lang takes precedence over the catalog's for its content. Common mistake: forgetting the title; without dc:title in the XMP and without DisplayDocTitle, PDF/UA rejects the document.

Conclusion

A tagged PDF adds a logical structure to the pages (/StructTreeRoot with Document, H1, P, Table, TH, TD, Figure and Link elements), linked to the content through sequences marked with MCIDs and a parent tree that provides the reverse path. PDF/UA adds the rules that make that structure accessible: language, visible title, alternative text, artifacts for decoration, table headers and described links. With Tagger, all of this boils down to wrapping each drawing operation in mark or artifact and calling finish, and veraPDF confirms that the accessible invoice complies with PDF/UA-1 (and PDF/A-2a).

So far we've generated invoices one at a time. But Nebula Distribution issues thousands a month, and every PDF/A, accessible or signed invoice costs time and memory. In the next lesson we'll measure exactly how much: we'll see how PDFBox manages memory, which caches it uses, how to reduce file size and how to generate 10,000 invoices in parallel without running out of heap.

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