Nebula Distribution has to keep its invoices for years, and nothing guarantees that a decade from now whatever viewer is in use will know how to handle a non-embedded font, a colour without a profile or a file that depends on an external resource. PDF/A (ISO 19005) solves that problem: it's a subset of PDF in which everything needed to reproduce the document travels inside the file, and anything that might stop working is forbidden. In this first lesson of the final module we'll turn InvoiceLab's invoices into PDF/A-1b, 2b, 2u and 3b; in PDF/A-3 we'll also attach the invoice data as XML; we'll validate the results with Preflight, PDFBox's validator, and with veraPDF, the reference validator; and we'll learn why the right order is always PDF/A first, signature second.

Contents

  1. What PDF/A is and what it's for
  2. Parts and conformance levels
  3. What PDF/A requires of a document
  4. Dependencies and the sRGB colour profile
  5. The PdfAConverter class
  6. XMP metadata for PDF/A
  7. Adapting InvoiceGenerator: the PdfAInvoiceGenerator decorator
  8. PDF/A-3 with the invoice as XML
  9. Validating with Preflight and veraPDF
  10. Signing after converting

What PDF/A is and what it's for

PDF/A ("A" for archive) isn't a different format: it's an ordinary PDF that gives up certain features and must include certain data. Any viewer can open it, but it also comes with these guarantees:

  • Self-contained: fonts, colour profiles and metadata live inside the file; nothing depends on the system it's opened on.
  • Device-independent: colours are defined by an ICC profile, so they look the same on any screen or printer.
  • No dynamic behaviour: no JavaScript, no downloaded content and no encryption whose key could be lost.
  • Self-describing: XMP metadata with a schema that declares the part and level of the standard.

It's used by public administrations, court archives, libraries and, in general, by any organisation that has to keep documents with legal value. For InvoiceLab it's the natural way to archive issued invoices, especially signed ones.

Parts and conformance levels

The standard has several parts (versions) and, within each one, several conformance levels:

Variant Based on Essentials Transparency Attachments
PDF/A-1b (2005) PDF 1.4 Reliable visual reproduction No No
PDF/A-1a PDF 1.4 1b + tagged structure and Unicode (accessible) No No
PDF/A-2b (2011) PDF 1.7 Visual reproduction; allows JPEG 2000, layers, object streams Yes Other PDF/A files only
PDF/A-2u PDF 1.7 2b + all text with a Unicode mapping (searchable and copyable) Yes Other PDF/A files only
PDF/A-2a PDF 1.7 2u + tagged PDF Yes Other PDF/A files only
PDF/A-3b/3u/3a (2012) PDF 1.7 Like part 2 Yes Any file (XML, CSV...)
PDF/A-4 (2020) PDF 2.0 New generation; drops the b/u/a levels Yes Variants 4f and 4e
  • The letter means: b = basic (visual appearance), u = unicode, a = accessible.
  • For invoices generated with PDFBox, PDF/A-2b or 2u is the most balanced choice. PDF/A-3b is the one to pick when the structured data has to be attached (it's the basis of Factur-X/ZUGFeRD).
  • PDF/A-1b still turns up in older tender specifications; it's the most restrictive.
  • Level a requires a tagged PDF, which is precisely the subject of the next lesson.

In code we represent the levels InvoiceLab can produce with an enum in the new com.invoicelab.archive package:

package com.invoicelab.archive;

/** PDF/A levels that InvoiceLab can produce. */
public enum PdfALevel {
    PDF_A_1B(1, "B"), PDF_A_2B(2, "B"), PDF_A_2U(2, "U"), PDF_A_3B(3, "B");

    private final int part;
    private final String conformance;

    PdfALevel(int part, String conformance) {
        this.part = part;
        this.conformance = conformance;
    }

    public int part() { return part; }
    public String conformance() { return conformance; }

    /** PDF/A-1 forbids transparency; PDF/A-2 and 3 allow it. */
    public boolean allowsTransparency() { return part >= 2; }

    /** PDF/A-1 is based on PDF 1.4: no object streams or compressed xref tables. */
    public boolean allowsObjectStreams() { return part >= 2; }

    /** Only PDF/A-3 allows attaching files of any type (XML, CSV...). */
    public boolean allowsAttachments() { return part == 3; }

    @Override
    public String toString() { return "PDF/A-" + part + conformance.toLowerCase(); }
}

The three allows... questions keep the differences between parts in a single place; the rest of the code asks the level instead of comparing numbers.

What PDF/A requires of a document

Before writing any code, it's worth knowing what our invoice is missing. If we validate output/F-2026-0001.pdf (the one generated in 03-05) as PDF/A-1b, veraPDF responds:

6.1.4-3   Xref streams shall not be used
6.7.2-1   The document catalog dictionary of a conforming file shall contain the Metadata key...
6.2.3.3-1 DeviceRGB may be used only if the file has a PDF/A-1 OutputIntent that uses an RGB colour space
6.4-2     An XObject dictionary shall not contain the SMask key

Each error corresponds to a requirement. The table summarises the ones that affect InvoiceLab:

Requirement What it means InvoiceLab status
Embedded fonts All of them, including the standard 14 (Helvetica...) Met: DejaVu with PDType0Font (02-03)
Colour profile (OutputIntent) If DeviceRGB is used, an ICC profile must define it Missing
XMP metadata With pdfaid:part and pdfaid:conformance Partial: Metadata (04-06) doesn't declare PDF/A
Info = XMP Equivalent fields must match (mandatory in PDF/A-1) Met with Metadata.syncXmp
No transparency (PDF/A-1 only) No opacity, blend modes or /SMask The PNG logo has an alpha channel → /SMask
No object streams (PDF/A-1 only) Classic xref table PDFBox 3 saves as 1.6 with object streams
No encryption The trailer can't have /Encrypt Met as long as we don't use Protection
No JavaScript or launch actions Nothing executable Met
Unicode (u/a levels only) Every glyph mapped to Unicode (/ToUnicode) Met: PDType0Font generates it
Attachments Forbidden in part 1; PDF/A only in part 2; anything in part 3 with /AFRelationship We'll add them in PDF/A-3

As you can see, the work from earlier modules (embedded fonts, synchronised metadata) already covers half the way.

Dependencies and the sRGB colour profile

Add the preflight module to pom.xml (it includes xmpbox, which we've been using since 04-06):

<dependency>
    <groupId>org.apache.pdfbox</groupId>
    <artifactId>preflight</artifactId>
    <version>${pdfbox.version}</version>
</dependency>

The ICC profile describes mathematically what "red 255" means in our document. The invoices use RGB colours designed for screens, so the right profile is sRGB. You have three reliable sources:

Source How to get it Notes
PDFBox examples org/apache/pdfbox/resources/pdfa/sRGB.icc inside pdfbox-examples-<version>-sources.jar (or the PDFBox repository) littleCMS sRGB v2 profile, zlib licence (its COPYING and LICENSE-ZLIB files are included). It's the one used by the official CreatePDFA example
Java itself ICC_Profile.getInstance(ColorSpace.CS_sRGB).getData() No extra files; Preflight and veraPDF accept it too
International Color Consortium sRGB2014.icc (v2 version) at color.org The "official" reference

In InvoiceLab we copy the one from the PDFBox examples to src/main/resources/icc/sRGB.icc (6,922 bytes, version 2.3), with its licence files next to it. Keeping it on the classpath means the result doesn't depend on the JVM running the application. Use a v2 profile: PDF/A-1 doesn't accept ICC v4 profiles.

The PdfAConverter class

PdfAConverter takes an already generated document and adds what PDF/A requires. It has four responsibilities: diagnose, fix what can be fixed, declare (profile and XMP) and save with the right options. We start with the diagnosis:

public final class PdfAConverter {

    public static final String SRGB_PROFILE = "/icc/sRGB.icc";

    /** Lists what prevents converting the document to the requested level (empty = it can be converted). */
    public static List<String> problems(PDDocument document, PdfALevel level) throws IOException {
        List<String> problems = new ArrayList<>();
        if (document.isEncrypted()) {
            problems.add("The document is encrypted: PDF/A doesn't allow encryption");
        }
        for (ResourceInventory.FoundFont font : ResourceInventory.fonts(document)) {
            if (!font.embedded()) {
                problems.add("Font not embedded: " + font.name() + " (pages " + font.pages() + ")");
            }
        }
        PDDocumentNameDictionary names = document.getDocumentCatalog().getNames();
        if (names != null && names.getJavaScript() != null) {
            problems.add("The document contains JavaScript");
        }
        if (!level.allowsTransparency()) {
            int n = 1;
            for (PDPage page : document.getPages()) {
                findTransparency(page.getResources(), n++, problems);
            }
        }
        return problems;
    }

    private static void findTransparency(PDResources resources, int page, List<String> problems)
            throws IOException {
        if (resources == null) {
            return;
        }
        for (COSName name : resources.getExtGStateNames()) {
            PDExtendedGraphicsState state = resources.getExtGState(name);
            Float fill = state.getNonStrokingAlphaConstant();
            Float stroke = state.getStrokingAlphaConstant();
            if ((fill != null && fill < 1f) || (stroke != null && stroke < 1f)
                    || state.getCOSObject().containsKey(COSName.SMASK)) {
                problems.add("Transparency in graphics state /" + name.getName() + " (page " + page + ")");
            }
        }
    }
  • We reuse ResourceInventory.fonts (06-03), which already walks through pages and Form XObjects and reports whether each font is embedded. If you add text to a page with PDType1Font(Standard14Fonts.FontName.HELVETICA), problems returns [Font not embedded: Helvetica (pages [1])].
  • Transparency in a graphics state (Shapes.opacity, 02-05, or the stamps from 04-02) can't be fixed automatically: changing the opacity changes the appearance. That's why it's only reported.
  • Images with /SMask, on the other hand, can be fixed without changing their appearance, as we'll see in a moment.

The public apply method chains everything together:

    public static void apply(PDDocument document, PdfALevel level) throws IOException {
        List<String> problems = problems(document, level);
        if (!problems.isEmpty()) {
            throw new IOException("Cannot convert to " + level + ": " + problems);
        }
        if (!level.allowsTransparency()) {
            flattenMasks(document);
        }
        addSrgbProfile(document);
        writeXmp(document, level);
    }

The colour profile as an OutputIntent

    static void addSrgbProfile(PDDocument document) throws IOException {
        PDDocumentCatalog catalog = document.getDocumentCatalog();
        if (!catalog.getOutputIntents().isEmpty()) {
            return;                                          // it already has one: don't duplicate it
        }
        try (InputStream profile = PdfAConverter.class.getResourceAsStream(SRGB_PROFILE)) {
            if (profile == null) {
                throw new IOException("ICC profile not found on the classpath: " + SRGB_PROFILE);
            }
            PDOutputIntent intent = new PDOutputIntent(document, profile);
            intent.setInfo("sRGB IEC61966-2.1");
            intent.setOutputCondition("sRGB IEC61966-2.1");
            intent.setOutputConditionIdentifier("sRGB IEC61966-2.1");
            intent.setRegistryName("http://www.color.org");
            catalog.addOutputIntent(intent);
        }
    }

PDOutputIntent creates an /OutputIntent dictionary with the subtype /GTS_PDFA1 (the same for every part) and copies the profile into a /DestOutputProfile stream. From then on, all the DeviceRGB in the document is interpreted as sRGB. A document should have only one PDF/A profile, hence the initial check.

Removing transparency from the logo (PDF/A-1 only)

Nebula's logo is an RGBA PNG. LosslessFactory (02-06) stores the alpha channel as a separate image linked through /SMask, which PDF/A-1 forbids. Since the logo is drawn on a white background, we can composite it onto white and replace it:

    static void flattenMasks(PDDocument document) throws IOException {
        Map<COSStream, PDImageXObject> replacements = new IdentityHashMap<>();
        for (PDPage page : document.getPages()) {
            PDResources resources = page.getResources();
            for (COSName name : resources.getXObjectNames()) {
                PDXObject object = resources.getXObject(name);
                if (object instanceof PDImageXObject image && image.getCOSObject().containsKey(COSName.SMASK)) {
                    PDImageXObject opaque = replacements.get(image.getCOSObject());
                    if (opaque == null) {                    // the same image is shared between pages
                        opaque = LosslessFactory.createFromImage(document, onWhite(image.getImage()));
                        replacements.put(image.getCOSObject(), opaque);
                    }
                    resources.put(name, opaque);             // same name /Im1: the content stream doesn't change
                }
            }
        }
    }

    private static BufferedImage onWhite(BufferedImage withAlpha) {
        BufferedImage opaque = new BufferedImage(withAlpha.getWidth(), withAlpha.getHeight(), BufferedImage.TYPE_INT_RGB);
        Graphics2D g = opaque.createGraphics();
        try {
            g.setColor(Color.WHITE);
            g.fillRect(0, 0, opaque.getWidth(), opaque.getHeight());
            g.drawImage(withAlpha, 0, 0, null);              // the alpha is blended with the white
        } finally {
            g.dispose();
        }
        return opaque;
    }
  • image.getImage() returns an ARGB BufferedImage with the /SMask already applied as its alpha channel.
  • The IdentityHashMap (as in ResourceInventory) ensures that the logo, shared by page 1 and the following pages, is converted only once.
  • resources.put(name, opaque) replaces the resource under the same name, so the /Im1 Do operator in the content stream keeps working without being touched.
  • A deliberate limitation: it only looks at page resources. If your documents have images inside Form XObjects, walk through them the way ResourceInventory does.

Saving according to the level

    public static byte[] save(PDDocument document, PdfALevel level) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        if (level.allowsObjectStreams()) {
            document.save(output);                                     // 1.6 with object streams
        } else {
            document.getDocument().setVersion(1.4f);
            document.save(output, CompressParameters.NO_COMPRESSION);  // classic xref, no object streams
        }
        return output.toByteArray();
    }

Remember (01-05) that PDFBox 3 saves with object streams and a compressed xref table by default. That's fine for PDF/A-2 and 3, but PDF/A-1 forbids it: if you save a valid PDF/A-1b with a normal save(), it stops being valid (Preflight: 1.4 Trailer Syntax error, /XRef cross reference streams are not allowed). CompressParameters.NO_COMPRESSION turns off object streams; the content streams are still Flate-compressed.

XMP metadata for PDF/A

The PDF/A XMP must include the pdfaid identification schema. In addition, back in 04-06 we left one question open: the custom Info keys (InvoiceNumber, CustomerVatId, Total) can only appear in XMP if a PDF/A extension schema describes their namespace. If you write a custom property without describing it, veraPDF rejects it (6.6.2.3.1-1 All properties specified in XMP form shall use either the predefined schemas...) and so does Preflight (7.3 Cannot find a definition for the namespace...).

    public static final String INVOICE_NS = "https://invoicelab.example/ns/invoice/1.0/";
    public static final String INVOICE_PREFIX = "il";
    private static final List<String> CUSTOM_KEYS = List.of("InvoiceNumber", "CustomerVatId", "Total");

    static void writeXmp(PDDocument document, PdfALevel level) throws IOException {
        Metadata.syncXmp(document);                             // Info = source of truth (04-06)
        XMPMetadata xmp = Metadata.readXmp(document);

        PDFAIdentificationSchema id = xmp.createAndAddPDFAIdentificationSchema();
        id.setPart(level.part());
        try {
            id.setConformance(level.conformance());
        } catch (BadFieldValueException e) {
            throw new IllegalStateException(e);                 // "A", "B" or "U": can't happen
        }

        PDDocumentInformation info = document.getDocumentInformation();
        if (info.getCustomMetadataValue(CUSTOM_KEYS.get(0)) != null) {
            XMPSchema custom = xmp.createAndAddDefaultSchema(INVOICE_PREFIX, INVOICE_NS);
            for (String key : CUSTOM_KEYS) {
                String value = info.getCustomMetadataValue(key);
                if (value != null) {
                    custom.setTextPropertyValue(key, value);
                }
            }
            describeCustomSchema(xmp);
        }

        ByteArrayOutputStream output = new ByteArrayOutputStream();
        try {
            new XmpSerializer().serialize(xmp, output, true);
        } catch (TransformerException e) {
            throw new IOException("Could not serialize the XMP", e);
        }
        PDMetadata metadata = new PDMetadata(document);
        metadata.importXMPMetadata(output.toByteArray());
        document.getDocumentCatalog().setMetadata(metadata);
    }
  • We start from Metadata.syncXmp, which already maps Info to Dublin Core, Adobe PDF and XMP Basic. That way Info and XMP match by construction.
  • createAndAddDefaultSchema(prefix, namespace) creates a generic schema to which text properties can be added.

The extension schema uses the pdfaSchema/pdfaProperty vocabulary to describe what il: is and which properties it has:

    private static void describeCustomSchema(XMPMetadata xmp) {
        PDFAExtensionSchema extension = xmp.createAndAddPDFAExtensionSchemaWithDefaultNS();
        extension.addNamespace("http://www.aiim.org/pdfa/ns/schema#", "pdfaSchema");
        extension.addNamespace("http://www.aiim.org/pdfa/ns/property#", "pdfaProperty");

        PDFASchemaType schema = new PDFASchemaType(xmp);
        schema.addProperty(schema.createTextType(PDFASchemaType.SCHEMA, "InvoiceLab invoice data"));
        schema.addProperty(schema.createTextType(PDFASchemaType.NAMESPACE_URI, INVOICE_NS));
        schema.addProperty(schema.createTextType(PDFASchemaType.PREFIX, INVOICE_PREFIX));

        ArrayProperty properties = schema.createArrayProperty(PDFASchemaType.PROPERTY, Cardinality.Seq);
        for (String key : CUSTOM_KEYS) {
            PDFAPropertyType property = new PDFAPropertyType(xmp);
            property.addProperty(property.createTextType(PDFAPropertyType.NAME, key));
            property.addProperty(property.createTextType(PDFAPropertyType.VALUETYPE, "Text"));
            property.addProperty(property.createTextType(PDFAPropertyType.CATEGORY, "external"));
            property.addProperty(property.createTextType(PDFAPropertyType.DESCRIPTION,
                    "Invoice field: " + key));
            properties.getContainer().addProperty(property);
        }
        schema.addProperty(properties);
        extension.addBagValue(PDFAExtensionSchema.SCHEMAS, schema);
    }

The result, abridged, is this XMP (you can view it with PDFDebugger, 01-05):

<rdf:Description rdf:about="">
  <pdfaid:part>2</pdfaid:part>
  <pdfaid:conformance>B</pdfaid:conformance>
</rdf:Description>
<rdf:Description xmlns:il="https://invoicelab.example/ns/invoice/1.0/" rdf:about="">
  <il:InvoiceNumber>F-2026-0001</il:InvoiceNumber>
  <il:CustomerVatId>J00000000</il:CustomerVatId>
  <il:Total>4193.94</il:Total>
</rdf:Description>
<rdf:Description xmlns:pdfaExtension="http://www.aiim.org/pdfa/ns/extension/" rdf:about="">
  <pdfaExtension:schemas>
    <rdf:Bag>
      <rdf:li rdf:parseType="Resource">
        <pdfaSchema:schema>InvoiceLab invoice data</pdfaSchema:schema>
        <pdfaSchema:namespaceURI>https://invoicelab.example/ns/invoice/1.0/</pdfaSchema:namespaceURI>
        <pdfaSchema:prefix>il</pdfaSchema:prefix>
        <pdfaSchema:property><rdf:Seq> ... one entry per property ... </rdf:Seq></pdfaSchema:property>
      </rdf:li>
    </rdf:Bag>
  </pdfaExtension:schemas>
</rdf:Description>

Info versus XMP depending on the part. In our tests, both validators rejected a PDF/A-1b whose Title differed between Info and XMP (Preflight: 7.2 Title present in the document catalog dictionary doesn't match with XMP information). veraPDF, however, accepts that difference in PDF/A-2b, because parts 2 and 3 no longer require it. Even so, keep them in sync: other programs read one or the other.

Adapting InvoiceGenerator: the PdfAInvoiceGenerator decorator

What has to change in InvoiceGenerator for it to produce PDF/A? Surprisingly little, thanks to decisions made in earlier modules:

Aspect PDF/A-2b / 3b PDF/A-1b
Fonts (InvoiceLabFonts) Nothing: they're already embedded Nothing
PNG logo with alpha (/SMask) Allowed Flattened onto white (flattenMasks)
Shapes.opacity, semi-transparent stamps Allowed Forbidden: they must be drawn opaque
Saving Normal No object streams, version 1.4
sRGB profile and XMP with pdfaid Added Added
Attachments Only in 3b Forbidden

Since the differences are applied after the pages are composed, we don't touch BaseGenerator or the blocks. We use the decorator pattern: a class that implements DocumentGenerator<Invoice>, delegates generation to another generator and transforms the result.

package com.invoicelab.archive;

public final class PdfAInvoiceGenerator implements DocumentGenerator<Invoice> {

    private static final ZoneId MADRID = ZoneId.of("Europe/Madrid");

    private final DocumentGenerator<Invoice> base;
    private final PdfALevel level;
    private final Clock clock;

    public PdfAInvoiceGenerator(DocumentGenerator<Invoice> base, PdfALevel level, Clock clock) {
        this.base = base;
        this.level = level;
        this.clock = clock;
    }

    @Override
    public byte[] generate(Invoice invoice) throws IOException {
        byte[] normal = base.generate(invoice);                     // 1) the usual invoice
        try (PDDocument document = Loader.loadPDF(normal)) {
            ZonedDateTime now = ZonedDateTime.now(clock.withZone(MADRID));
            Metadata.forInvoice(document, invoice, now);             // 2) metadata (04-06)
            document.getDocumentInformation().setModificationDate(GregorianCalendar.from(now));

            if (level.allowsAttachments()) {                         // 3) PDF/A-3 only
                String name = "invoice-" + invoice.number() + ".xml";
                PdfAConverter.attach(document, name, InvoiceXml.generate(invoice), "application/xml",
                        "Structured data for invoice " + invoice.number(),
                        PdfAConverter.Relationship.Alternative, GregorianCalendar.from(now));
            }
            PdfAConverter.apply(document, level);                    // 4) profile, XMP, masks
            return PdfAConverter.save(document, level);              // 5) with the level's options
        }
    }
}
  • The decorator accepts any DocumentGenerator<Invoice>: InvoiceGenerator today, another template tomorrow.
  • Because it implements the same interface, it inherits the generate(T, Path) method with atomic writing (03-04).
  • The Clock replaces a bare now(). Metadata.forInvoice sets the modification date with the real time; we overwrite it with the clock's time so that, in the tests in 08-05, a fixed clock produces identical metadata.
  • Loading and saving again costs a few milliseconds; in exchange, the original generator stays untouched. We'll measure these costs in 08-03.

The example program generates all four levels:

public class PdfAInvoice {

    public static void main(String[] args) throws IOException {
        Invoice invoice = SampleData.invoice(30);
        Path folder = Path.of("output/pdfa");
        for (PdfALevel level : PdfALevel.values()) {
            Path target = folder.resolve(invoice.number() + "-"
                    + level.name().toLowerCase().replace('_', '-') + ".pdf");
            new PdfAInvoiceGenerator(new InvoiceGenerator(Theme.nebula()), level, Clock.systemDefaultZone())
                    .generate(invoice, target);
            System.out.printf("%s → %s (%,d bytes)%n", level, target, Files.size(target));
        }
    }
}
PDF/A-1b → output/pdfa/F-2026-0001-pdf-a-1b.pdf (60,773 bytes)
PDF/A-2b → output/pdfa/F-2026-0001-pdf-a-2b.pdf (59,383 bytes)
PDF/A-2u → output/pdfa/F-2026-0001-pdf-a-2u.pdf (59,383 bytes)
PDF/A-3b → output/pdfa/F-2026-0001-pdf-a-3b.pdf (64,285 bytes)

The normal invoice was 52,410 bytes; the ICC profile and the XMP add about 7 KB. The 1b file is a bit heavier because it doesn't use object streams, and the 3b one because of the attached XML.

PDF/A-3 with the invoice as XML

PDF/A-3 lets you embed files of any type as long as they're declared as associated files: each with its MIME type, its date and its relationship to the document (/AFRelationship), and referenced from the catalog's /AF array. The idea is that the PDF is the human-readable representation and the XML the machine-processable one.

/AFRelationship Meaning
Source The file is the source of the PDF (e.g. the original spreadsheet)
Data Data used to generate visual content (tables, charts)
Alternative An alternative representation of the same content
Supplement Supplementary information
Unspecified Unknown or not applicable

InvoiceXml.generate(Invoice) (in com.invoicelab.archive) produces a simple XML document with its own, fictional namespace, urn:invoicelab:invoice:1.0: issuer, customer, one <line> per line and the totals, with amounts in toPlainString() format and with &, <, >, " and ' escaped. What matters here is how it's attached:

    public enum Relationship { Source, Data, Alternative, Supplement, Unspecified }

    public static void attach(PDDocument document, String name, byte[] data, String mimeType,
                              String description, Relationship relationship, Calendar date) throws IOException {
        PDEmbeddedFile embedded = new PDEmbeddedFile(document, new ByteArrayInputStream(data));
        embedded.setSubtype(mimeType);                         // /Subtype /application#2Fxml
        embedded.setSize(data.length);                         // /Params << /Size ... >>
        embedded.setCreationDate(date);
        embedded.setModDate(date);                             // /ModDate: mandatory in PDF/A-3

        PDComplexFileSpecification spec = new PDComplexFileSpecification();
        spec.setFile(name);                                    // /F
        spec.setFileUnicode(name);                             // /UF
        spec.setFileDescription(description);                  // /Desc
        spec.setEmbeddedFile(embedded);                        // /EF << /F ... >>
        spec.setEmbeddedFileUnicode(embedded);                 // /EF << /UF ... >>
        spec.getCOSObject().setName(COSName.AF_RELATIONSHIP, relationship.name());

        PDDocumentCatalog catalog = document.getDocumentCatalog();
        PDDocumentNameDictionary names = catalog.getNames();
        if (names == null) {
            names = new PDDocumentNameDictionary(catalog);
            catalog.setNames(names);
        }
        PDEmbeddedFilesNameTreeNode tree = names.getEmbeddedFiles();
        if (tree == null) {
            tree = new PDEmbeddedFilesNameTreeNode();
            names.setEmbeddedFiles(tree);
        }
        Map<String, PDComplexFileSpecification> existing = tree.getNames() == null
                ? new TreeMap<>() : new TreeMap<>(tree.getNames());
        existing.put(name, spec);
        tree.setNames(existing);                               // name trees are kept sorted

        COSArray af = catalog.getCOSObject().getCOSArray(COSName.AF);
        if (af == null) {
            af = new COSArray();
            catalog.getCOSObject().setItem(COSName.AF, af);
        }
        af.add(spec);                                          // file associated with the document
    }
  • The file is linked twice: in the /EmbeddedFiles tree (so that viewers show it in their attachments panel) and in /AF (to declare its relationship with the document).
  • PDFBox 3.0 has no setAFRelationship method; we use the COSName.AF_RELATIONSHIP constant and write the name directly.
  • setNames replaces all the entries, which is why we first copy the existing ones into a TreeMap.

Reading it back is just as easy:

PDEmbeddedFilesNameTreeNode tree = document.getDocumentCatalog().getNames().getEmbeddedFiles();
for (Map.Entry<String, PDComplexFileSpecification> e : tree.getNames().entrySet()) {
    PDEmbeddedFile file = e.getValue().getEmbeddedFile();
    System.out.println(e.getKey() + " " + file.getSubtype() + " " + file.getSize() + " B");
    String xml = new String(file.toByteArray(), StandardCharsets.UTF_8);
}
invoice-F-2026-0001.xml application/xml 4607 B

Factur-X, ZUGFeRD and e-invoicing. Factur-X (France) and ZUGFeRD (Germany) are precisely PDF/A-3 with an attached XML in UN/CEFACT CII format under a fixed name, with a specific relationship and their own XMP extension schema (fx:). Our XML follows none of those standards, nor Facturae, the Spanish public administration's format. If your invoices have tax implications, check the current e-invoicing regulations in each country (obligations, accepted formats, verification systems) and consult an adviser before choosing a format.

Validating with Preflight and veraPDF

Generating "something like" PDF/A is easy; proving that it is PDF/A takes a validator. There are two in the Java ecosystem:

Validator Parts it validates Usage Notes
PDFBox Preflight PDF/A-1b only (and part of 1a) Library (preflight) and pdfbox-app subcommand Lightweight; useful for PDF/A-1b
veraPDF PDF/A-1, 2, 3 and 4, and PDF/UA CLI, GUI, REST service and Java library Reference validator, backed by the PDF Association

We wrap both in PdfAValidator:

public final class PdfAValidator {

    public record Report(String validator, boolean valid, List<String> errors) {
    }

    /** Validates with PDFBox Preflight. Careful: Preflight only knows PDF/A-1b (and 1a). */
    public static Report preflight(Path pdf) throws IOException {
        ValidationResult result = PreflightParser.validate(pdf.toFile());
        List<String> errors = new ArrayList<>();
        for (ValidationResult.ValidationError error : result.getErrorsList()) {
            errors.add(error.getErrorCode() + " " + error.getDetails()
                    + (error.getPageNumber() != null ? " (page " + (error.getPageNumber() + 1) + ")" : ""));
        }
        return new Report("Preflight", result.isValid(), errors);
    }
}
  • PreflightParser.validate(File) is the PDFBox 3 shortcut: it parses, validates and closes the document. In 2.x code you'll see PreflightParser parser = new PreflightParser(file); parser.parse(); PreflightDocument doc = parser.getPreflightDocument(); doc.validate();, which no longer exists in that form in 3.x.
  • Each ValidationError carries a code (2.4.3, 7.2...) identifying the rule, the details and, where relevant, the page (0-based).

For PDF/A-2 and 3 we need veraPDF. You can use its command-line tool (verapdf --flavour 2b invoice.pdf) or integrate it as a library. The second option, verified with org.verapdf:validation-model-jakarta:1.28.1, looks like this:

    public static Report veraPdf(Path pdf) throws IOException {
        VeraGreenfieldFoundryProvider.initialise();                  // once per JVM is enough
        try (InputStream input = Files.newInputStream(pdf);
             PDFAParser parser = Foundries.defaultInstance().createParser(input);
             PDFAValidator validator = Foundries.defaultInstance().createValidator(parser.getFlavour(), false)) {
            org.verapdf.pdfa.results.ValidationResult result = validator.validate(parser);
            List<String> errors = new ArrayList<>();
            for (TestAssertion a : result.getTestAssertions()) {
                if (a.getStatus() == TestAssertion.Status.FAILED) {
                    errors.add(a.getRuleId().getClause() + "-" + a.getRuleId().getTestNumber() + " " + a.getMessage());
                }
            }
            return new Report("veraPDF " + parser.getFlavour(), result.isCompliant(), errors);
        } catch (Exception e) {
            throw new IOException("veraPDF could not validate " + pdf + ": " + e.getMessage(), e);
        }
    }

parser.getFlavour() reads the declared part and level (1b, 2b, 3b...) from the XMP, so veraPDF validates against what the file claims to be. The results with our invoices:

PDF/A-1b → Preflight: VALID · veraPDF 1b: VALID
PDF/A-2b → veraPDF 2b: VALID
PDF/A-2u → veraPDF 2u: VALID
PDF/A-3b → veraPDF 3b: VALID

And these are the errors we got when deliberately "breaking" each requirement:

Experiment Preflight (1b) veraPDF
1b saved with a normal save() 1.4 /XRef cross reference streams are not allowed 6.1.4-3 Xref streams shall not be used
1b without flattening the logo 2.2.2 Soft Mask must be null or None 6.4-2 An XObject dictionary shall not contain the SMask key
2b without OutputIntent 2.4.3 DestOutputProfile is missing 6.2.4.3-2 DeviceRGB shall only be used if...
2b with text in Helvetica 3.1.3 FontFile entry is missing 6.2.11.4.1-1 The font programs for all fonts... shall be embedded
2b without extension schema 7.3 Cannot find a definition for the namespace 6.6.2.3.1-1 All properties specified in XMP form...
2b encrypted with Protection 1.4.2 The trailer dictionary contains Encrypt 6.1.3-2 The keyword Encrypt shall not be used
1b with Java's sRGB profile Valid Valid

Notice that Preflight, when given a PDF/A-2b or 3b, reports errors that aren't errors (7.11.2 part must be 1, /SMask, object streams, EmbeddedFile entry is present): it simply always validates against PDF/A-1b. Use it only for 1b.

veraPDF is the reference tool, but a successful validation doesn't replace a human check that the document looks the way it should: compare the normal and PDF/A versions with VisualComparator (06-04).

Signing after converting

Archived invoices are usually signed. The order matters:

flowchart LR
    A["InvoiceGenerator<br/>(bytes)"] --> B["PdfAInvoiceGenerator<br/>profile + XMP (+ XML)"]
    B --> C["PdfAValidator<br/>(veraPDF)"]
    C --> D["PdfSigner<br/>INCREMENTAL save"]
    D --> E["Archive"]
    X["Sign first and<br/>convert afterwards"] -. "full save:<br/>signature BROKEN" .-> E

We check it with PdfSigner (PADES_B profile) and SignatureVerifier from 07-03 and 07-04:

File Bytes veraPDF SignatureVerifier
Signed PDF/A-1b 100,124 Valid (and Preflight too) VALID
Signed PDF/A-2b 98,635 Valid VALID
Signed PDF/A-3b 103,565 Valid VALID
Signed and then converted to 2b 61,866 6.4.3-1 When computing the digest... BROKEN
Signed PDF/A-2b + incremental "PAID" stamp (04-02) 109,025 Valid Later changes
  • PdfSigner's signature is an incremental save that adds an invisible signature field: it changes nothing PDF/A requires, which is why the result is still valid.
  • Converting a signed PDF involves a full save (the catalog, the XMP and sometimes the images have to be rewritten): the signature breaks, as we saw in 07-04.
  • The "PAID" stamp uses opacity: it's valid in PDF/A-2b, but in PDF/A-1b Preflight would reject it (4.1.2 CA entry in a ExtGState is invalid).

Common Mistakes and Tips

  • Validating a PDF/A-2 or 3 with Preflight. It always responds with PDF/A-1 errors. For parts 2, 3 and 4, use veraPDF.
  • Saving a PDF/A-1 with a normal save(). PDFBox 3 writes object streams and the file stops conforming. Use CompressParameters.NO_COMPRESSION.
  • Declaring PDF/A in the XMP without complying. Setting pdfaid:part is just a promise; validate every new template before putting it into production.
  • Adding custom XMP properties without an extension schema. Every validator rejects it. Either describe them or leave them in Info only.
  • Changing Info and forgetting to regenerate the XMP. In PDF/A-1 it's an error; in the other parts, an inconsistency. Always call PdfAConverter.apply (or Metadata.syncXmp) after the last metadata change.
  • Using an ICC v4 profile in PDF/A-1 or adding two different OutputIntents. One sRGB v2 profile, and only one.
  • Converting after signing. It breaks the signature. PDF/A first, then the signature, and from then on only permitted incremental changes.
  • Encrypting archive documents. PDF/A doesn't allow it: protect the storage, not the file.
  • Tip: validate in the automated tests (08-05), not by hand. veraPDF takes a few hundred milliseconds per invoice: perfectly affordable in CI.

Exercises

Exercise 1. Write a program that converts the five PDFs from the January batch (output/2026-01/F-2026-000N.pdf, 04-04) to PDF/A-2b using PdfAConverter directly (no generator) and validates each one with veraPDF. The PDFs already exist: don't generate them again.

Exercise 2. Write Optional<byte[]> attachedXml(Path pdf, String name) that returns the content of the attached file with that name, or empty if it doesn't exist. Use it to check that the total in the XML of F-2026-0001-pdf-a-3b.pdf matches SampleData.invoice(30).total().

Exercise 3. Try converting the invoice stamped as "PAID" in 04-02 (output/F-2026-0001-paid.pdf) to PDF/A-1b. What happens? Suggest two solutions.

Solutions

Solution 1.

for (int n = 1; n <= 5; n++) {
    Path source = Path.of(String.format("output/2026-01/F-2026-%04d.pdf", n));
    Path target = Path.of(String.format("output/pdfa/batch/F-2026-%04d-2b.pdf", n));
    Files.createDirectories(target.getParent());
    try (PDDocument document = Loader.loadPDF(source.toFile())) {
        PdfAConverter.apply(document, PdfALevel.PDF_A_2B);
        Files.write(target, PdfAConverter.save(document, PdfALevel.PDF_A_2B));
    }
    PdfAValidator.Report report = PdfAValidator.veraPdf(target);
    System.out.println(target.getFileName() + ": " + (report.valid() ? "VALID" : report.errors()));
}

Without Metadata.forInvoice, the XMP will only contain whatever was in Info (Producer, dates...) plus pdfaid; it's valid, but thin. If you have the Invoice at hand, call Metadata.forInvoice first, as the decorator does. Typical mistake: saving a PDF/A-1 with document.save(target) (it doesn't matter here because it's 2b, but get into the habit of using PdfAConverter.save).

Solution 2.

static Optional<byte[]> attachedXml(Path pdf, String name) throws IOException {
    try (PDDocument document = Loader.loadPDF(pdf.toFile())) {
        PDDocumentNameDictionary names = document.getDocumentCatalog().getNames();
        if (names == null || names.getEmbeddedFiles() == null) {
            return Optional.empty();
        }
        Map<String, PDComplexFileSpecification> map = names.getEmbeddedFiles().getNames();
        PDComplexFileSpecification fs = map == null ? null : map.get(name);
        return fs == null || fs.getEmbeddedFile() == null
                ? Optional.empty() : Optional.of(fs.getEmbeddedFile().toByteArray());
    }
}

byte[] xml = attachedXml(Path.of("output/pdfa/F-2026-0001-pdf-a-3b.pdf"), "invoice-F-2026-0001.xml").orElseThrow();
String text = new String(xml, StandardCharsets.UTF_8);
Matcher m = Pattern.compile("total=\"([0-9.]+)\"").matcher(text);
System.out.println(m.find() && new BigDecimal(m.group(1)).compareTo(SampleData.invoice(30).total()) == 0);
// true

Compare with compareTo, not equals: BigDecimal.equals takes the scale into account (4193.94 versus 4193.940). In a real case you'd use an XML parser, not a regular expression. Bear in mind that in large name trees getNames() can be null at the root, with the entries in getKids(); with a single attachment, as here, that doesn't happen.

Solution 3. PdfAConverter.apply throws IOException: Cannot convert to PDF/A-1b: [Transparency in graphics state /gs1 (page 1)], because the Stamper stamp uses a PDExtendedGraphicsState with opacity. Solutions: (a) use PDF/A-2b, which allows transparency, or (b) stamp archive invoices in solid colour, without opacity, for example via a parameter in Stamper. What you should not do is manually remove the /CA key from the graphics state: the validator would be satisfied, but the stamp would cover the text underneath.

Conclusion

PDF/A turns a PDF into an archive document: embedded fonts, colours defined by an sRGB ICC profile, XMP metadata declaring the part and level (and describing our custom properties with an extension schema), nothing dynamic or encrypted and, in PDF/A-3, associated files such as the invoice XML. With PdfAConverter and the PdfAInvoiceGenerator decorator, InvoiceLab produces PDF/A-1b, 2b, 2u and 3b without touching the original generator, and with PdfAValidator it proves it: Preflight for PDF/A-1b, veraPDF for everything. And you've confirmed the order that can't be skipped: PDF/A first, then the signature.

PDF/A-2b guarantees that the invoice will look the same in twenty years' time, but not that everyone will be able to read it: to a screen reader, our invoice is still a heap of unstructured text with no headings, no tables and no description of the logo. In the next lesson we'll build tagged, accessible PDFs, the requirement of PDF/A's "a" level and of the PDF/UA standard.

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