A PDF isn't just what you see on its pages. When you open an invoice in the viewer and look at its properties, you see a title, an author, the application that created it, the creation date… This is the document metadata, and it's useful for much more than it seems: desktop search tools and document management systems index it, the viewer's title bar can show the title instead of a cryptic F-2026-0001.pdf, screen readers use the declared language to pronounce the text, and the PDF/A standard requires it to be consistent. It can also reveal information you didn't want to publish. In this final lesson of the module you'll learn to read and write PDF's two metadata systems (the document information dictionary and XMP), to keep them in sync, to declare the language, to configure how the document opens and to clean it up before publishing it. Everything will go into the Metadata class, the last one in the com.invoicelab.editing package.

Contents

  1. Two metadata systems: Info and XMP
  2. The document information dictionary with PDDocumentInformation
  3. Dates in PDF and Calendar
  4. Custom keys: InvoiceNumber
  5. XMP metadata with xmpbox
  6. Why Info and XMP must be kept in sync
  7. Language, viewer preferences and opening mode
  8. The Metadata class and the F-2026-0001 example
  9. Reading a PDF's metadata
  10. Privacy: cleaning metadata before publishing

Two metadata systems: Info and XMP

For historical reasons, a PDF can store its metadata in two ways:

flowchart LR
    T["Trailer"] -->|"/Info"| I["Document information dictionary<br/>/Title /Author /Subject /Keywords<br/>/Creator /Producer<br/>/CreationDate /ModDate<br/>+ custom keys"]
    T -->|"/Root"| C["Catalog"]
    C -->|"/Metadata"| X["XMP stream (XML)<br/>dc:title, dc:creator...<br/>pdf:Producer, pdf:Keywords<br/>xmp:CreateDate, xmp:ModifyDate..."]
    C -->|"/Lang"| L["en-GB"]
    C -->|"/ViewerPreferences"| V["/DisplayDocTitle true"]
Document information dictionary (Info) XMP
Where it lives Dictionary referenced by /Info in the trailer XML stream referenced by /Metadata in the catalog (and optionally in pages, images…)
Format PDF keys with strings and dates XML (RDF) with standard schemas: Dublin Core, Adobe PDF, XMP Basic…
Extensible Custom keys, no strings attached (/InvoiceNumber) With declared custom schemas (for PDF/A, with an extension schema)
Status Deprecated in PDF 2.0, except /CreationDate and /ModDate, but read universally The recommended system; mandatory in PDF/A
PDFBox class PDDocumentInformation PDMetadata (the stream) + the xmpbox library (the XML)

In practice, viewers and office software still mostly read Info, while archiving systems and PDF/A require XMP. That's why InvoiceLab will write both, with the same values.

The document information dictionary with PDDocumentInformation

document.getDocumentInformation() returns the document's PDDocumentInformation. If the PDF had no /Info dictionary, PDFBox creates an empty one and links it to the trailer, so it never returns null.

Method Key Recommended content in InvoiceLab
setTitle / getTitle /Title Invoice F-2026-0001
setAuthor /Author The issuer's company name
setSubject /Subject Short description: customer and amount
setKeywords /Keywords Keywords separated by ;
setCreator /Creator The application that created the content: InvoiceLab
setProducer /Producer The tool that generated the PDF: InvoiceLab (Apache PDFBox 3.0)
setCreationDate / setModificationDate /CreationDate, /ModDate Calendar (next section)
setTrapped /Trapped For print production only: True, False or Unknown
setCustomMetadataValue / getCustomMetadataValue Any other Custom keys (section 4)
getMetadataKeys() — All the keys present

Remember from lesson 01-04 that PDFBox doesn't fill in /Producer automatically: if you don't do it yourself, the field stays empty. And passing null to any setter removes the key.

Dates in PDF and Calendar

In the file, dates are strings with their own format:

D:20260115103000+01'00'
  │   │ │ │ │ │  └── offset from UTC: +01:00 (Spanish mainland time in winter)
  │   │ │ │ │ └──── seconds (00)
  │   │ │ │ └────── minutes (30)
  │   │ │ └──────── hour (10)
  │   │ └────────── day (15)
  │   └──────────── month (01)
  └──────────────── year (2026)

PDFBox converts that format to and from java.util.Calendar, Java's old date class. With the modern API (java.time), the conversion is straightforward:

ZonedDateTime issued = ZonedDateTime.of(2026, 1, 15, 10, 30, 0, 0, ZoneId.of("Europe/Madrid"));
info.setCreationDate(GregorianCalendar.from(issued));            // java.time → Calendar

Calendar read = info.getCreationDate();                          // Calendar → java.time
ZonedDateTime date = ZonedDateTime.ofInstant(read.toInstant(), ZoneId.of("Europe/Madrid"));
  • Always use a date with a time zone (ZonedDateTime), not LocalDateTime: that way the PDF stores the offset from UTC and the date is unambiguous in any country.
  • ZoneId.of("Europe/Madrid") automatically applies summer time (+02'00') or winter time (+01'00').
  • The creation date of an issued invoice is the issue date, not the moment you add the metadata. The modification date, on the other hand, is "now".

Custom keys: InvoiceNumber

The Info dictionary accepts custom keys. They're very useful so that other programs (a document management system, a script at the accountants) can identify the document without having to extract its text:

info.setCustomMetadataValue("InvoiceNumber", invoice.number());
info.setCustomMetadataValue("CustomerVatId", invoice.customer().taxId());
info.setCustomMetadataValue("Total", invoice.total().toPlainString());
  • The value is always a string. For the amount we use toPlainString() (4193.94) rather than Formats.euros (4.193,94 €): it's data for machines, and the format with a decimal point and no symbol is the one any program knows how to interpret.
  • In Acrobat they appear under Document Properties → Custom.
  • The difference from the /InvoiceLabStatus key we put in the catalog in 04-01: no viewer shows those private keys; these ones are shown, and they're the standard place for document metadata.
  • In XMP, custom properties require a schema with its own namespace and, for PDF/A, an extension schema that describes it. We'll look at this in lesson 08-01; here we stick to custom keys in Info.

XMP metadata with xmpbox

XMP (Extensible Metadata Platform) is an XML format based on RDF, standardised as ISO 16684. PDFBox handles it with the xmpbox library, a separate module that you need to add to pom.xml (if you did exercise 2 in lesson 01-02, you already have it):

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

The pieces:

Class Package Role
XMPMetadata org.apache.xmpbox The complete XMP document: XMPMetadata.createXMPMetadata()
DublinCoreSchema org.apache.xmpbox.schema The dc: schema (title, creators, description, format, language…)
AdobePDFSchema org.apache.xmpbox.schema The pdf: schema (Producer, Keywords, PDFVersion)
XMPBasicSchema org.apache.xmpbox.schema The xmp: schema (CreatorTool, CreateDate, ModifyDate, MetadataDate)
XmpSerializer org.apache.xmpbox.xml Turns the XMPMetadata into XML bytes
DomXmpParser org.apache.xmpbox.xml Turns XML bytes into XMPMetadata (reading)
PDMetadata org.apache.pdfbox.pdmodel.common The PDF stream holding the XML; attached to the catalog with setMetadata

The mapping between Info and XMP is defined by the specification:

Info XMP xmpbox method
/Title dc:title dc.setTitle(...)
/Author dc:creator (list) dc.addCreator(...)
/Subject dc:description dc.setDescription(...)
/Keywords pdf:Keywords pdf.setKeywords(...)
/Creator xmp:CreatorTool basic.setCreatorTool(...)
/Producer pdf:Producer pdf.setProducer(...)
/CreationDate xmp:CreateDate basic.setCreateDate(...)
/ModDate xmp:ModifyDate basic.setModifyDate(...)

Watch out for the naming traps: Info's author is Dublin Core's creator, whereas Info's Creator is XMP's CreatorTool.

Why Info and XMP must be kept in sync

If a document has both systems with different values (for example, because a tool changed the title in Info but not in XMP), each program will show a different one, and there's no way of knowing which is right. In addition:

  • PDF/A requires the equivalent Info and XMP values to match; a validator rejects the file if they don't (lesson 08-01).
  • Document management systems usually read XMP; viewers, Info. If they don't match, the user sees one title and the search engine indexes another.

InvoiceLab's strategy is simple: Info is the source of truth and, after any change to Info, XMP is regenerated from it by a single method, syncXmp. XMP is never edited separately.

Language, viewer preferences and opening mode

Three catalog settings complete the document's "record card":

Language (/Lang). Declares the main language of the text with a BCP 47 tag:

document.getDocumentCatalog().setLanguage("en-GB");

Screen readers use it to choose the voice and the pronunciation rules; it's an accessibility requirement (lesson 08-02) and a PDF/UA one. For a Spanish or Catalan version of the invoice you would use es-ES or ca-ES.

Viewer preferences (/ViewerPreferences). The most useful one is DisplayDocTitle: it makes the viewer's title bar show the document's title ("Invoice F-2026-0001") instead of the file name.

PDViewerPreferences preferences = catalog.getViewerPreferences();
if (preferences == null) {
    preferences = new PDViewerPreferences(new COSDictionary());
    catalog.setViewerPreferences(preferences);
}
preferences.setDisplayDocTitle(true);

Other PDViewerPreferences options: setFitWindow (fit the window to the page), setHideToolbar, setDuplex (a double-sided printing hint) or setPrintScaling (stop the print dialog from scaling the page, useful for labels).

Opening mode and layout. They specify which panel opens and how the pages are displayed:

Method Values (enum) Example of use
catalog.setPageMode(PageMode) USE_NONE, USE_OUTLINES, USE_THUMBS, FULL_SCREEN, USE_OPTIONAL_CONTENT, USE_ATTACHMENTS USE_OPTIONAL_CONTENT for the invoice with layers from 04-05; USE_OUTLINES for a batch with bookmarks (06-05)
catalog.setPageLayout(PageLayout) SINGLE_PAGE, ONE_COLUMN, TWO_COLUMN_LEFT, TWO_COLUMN_RIGHT, TWO_PAGE_LEFT, TWO_PAGE_RIGHT TWO_PAGE_RIGHT for the double-sided batch from 04-04: odd pages sit on the right, as on paper

They're suggestions: the viewer may ignore them or the user may change them.

The Metadata class and the F-2026-0001 example

package com.invoicelab.editing;

// imports: Invoice, Formats, ByteArrayOutputStream, IOException, InputStream, ZoneId, ZonedDateTime,
//          ArrayList, Calendar, GregorianCalendar, List, TransformerException, COSDictionary, COSName,
//          PDDocument, PDDocumentCatalog, PDDocumentInformation, PDPage, PageLayout, PageMode, PDMetadata,
//          PDViewerPreferences, XMPMetadata, AdobePDFSchema, DublinCoreSchema, XMPBasicSchema,
//          DomXmpParser, XmpParsingException, XmpSerializer

/** Document metadata: information dictionary, XMP, language and viewer preferences. */
public final class Metadata {

    public static final String CREATOR = "InvoiceLab";
    public static final String PRODUCER = "InvoiceLab (Apache PDFBox 3.0)";
    private static final ZoneId MADRID = ZoneId.of("Europe/Madrid");

    private Metadata() {
    }

    /** Fills in an invoice's metadata and syncs it into XMP. */
    public static void forInvoice(PDDocument document, Invoice invoice, ZonedDateTime issued) throws IOException {
        PDDocumentInformation info = document.getDocumentInformation();
        info.setTitle("Invoice " + invoice.number());
        info.setAuthor(invoice.issuer().companyName());
        info.setSubject("Invoice " + invoice.number() + " to " + invoice.customer().companyName()
                + " for " + Formats.euros(invoice.total()));
        info.setKeywords(String.join("; ", "invoice", invoice.number(), invoice.customer().taxId()));
        info.setCreator(CREATOR);
        info.setProducer(PRODUCER);
        info.setCreationDate(GregorianCalendar.from(issued));
        info.setModificationDate(GregorianCalendar.from(ZonedDateTime.now(MADRID)));
        // Custom keys: not standard, but any program can read them
        info.setCustomMetadataValue("InvoiceNumber", invoice.number());
        info.setCustomMetadataValue("CustomerVatId", invoice.customer().taxId());
        info.setCustomMetadataValue("Total", invoice.total().toPlainString());

        syncXmp(document);

        PDDocumentCatalog catalog = document.getDocumentCatalog();
        catalog.setLanguage("en-GB");
        PDViewerPreferences preferences = catalog.getViewerPreferences();
        if (preferences == null) {
            preferences = new PDViewerPreferences(new COSDictionary());
            catalog.setViewerPreferences(preferences);
        }
        preferences.setDisplayDocTitle(true);           // the viewer's title bar shows the title, not the file
        catalog.setPageMode(PageMode.USE_NONE);
        catalog.setPageLayout(PageLayout.SINGLE_PAGE);
    }

    /** Writes into XMP the same values as those in the information dictionary. */
    public static void syncXmp(PDDocument document) throws IOException {
        PDDocumentInformation info = document.getDocumentInformation();
        XMPMetadata xmp = XMPMetadata.createXMPMetadata();

        DublinCoreSchema dc = xmp.createAndAddDublinCoreSchema();
        if (info.getTitle() != null) {
            dc.setTitle(info.getTitle());
        }
        if (info.getAuthor() != null) {
            dc.addCreator(info.getAuthor());
        }
        if (info.getSubject() != null) {
            dc.setDescription(info.getSubject());
        }
        dc.setFormat("application/pdf");

        AdobePDFSchema pdf = xmp.createAndAddAdobePDFSchema();
        if (info.getKeywords() != null) {
            pdf.setKeywords(info.getKeywords());
        }
        if (info.getProducer() != null) {
            pdf.setProducer(info.getProducer());
        }

        XMPBasicSchema basic = xmp.createAndAddXMPBasicSchema();
        if (info.getCreator() != null) {
            basic.setCreatorTool(info.getCreator());
        }
        if (info.getCreationDate() != null) {
            basic.setCreateDate(info.getCreationDate());
        }
        if (info.getModificationDate() != null) {
            basic.setModifyDate(info.getModificationDate());
            basic.setMetadataDate(info.getModificationDate());
        }

        PDMetadata metadata = new PDMetadata(document);
        metadata.importXMPMetadata(serialize(xmp));
        document.getDocumentCatalog().setMetadata(metadata);
    }

    private static byte[] serialize(XMPMetadata xmp) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        try {
            new XmpSerializer().serialize(xmp, output, true);
        } catch (TransformerException e) {
            throw new IOException("Could not serialise the XMP", e);
        }
        return output.toByteArray();
    }

    // readXmp, clean and text: in sections 9 and 10
}

Key points:

  • forInvoice receives the model (Invoice) as well as the document: the metadata comes from the data, not from the PDF's text. It's the same philosophy as in module 3: the model is the source of truth.
  • The Subject uses Formats.euros because it's text for people; the Total key, by contrast, is for machines.
  • syncXmp creates a new XMP every time (it doesn't edit the previous one): that way no leftovers of old values ever remain. Each if avoids writing empty properties when Info doesn't have that key.
  • dc.setTitle(String) stores the title as the default-language value (xml:lang="x-default"); Dublin Core allows titles in several languages with addTitle(language, text).
  • MetadataDate is the date of the last modification of the metadata; when it's regenerated it matches the modification date.
  • serialize(xmp, output, true): the true adds the <?xpacket ...?> wrapper, which lets other tools locate the XMP inside the file even if they don't understand PDF. The TransformerException (from Java's XML API) is converted into an IOException so that InvoiceLab's methods only throw one type of exception.
  • PDMetadata is a PDF stream; importXMPMetadata writes the XML bytes into it uncompressed, as the specification recommends so that the XMP can be read by external tools.

The InvoiceMetadata program applies the metadata to the issued invoice in incremental mode (the original revision stays intact) and shows it before and after:

Invoice invoice = SampleData.invoice(30);                   // the same F-2026-0001 as in module 3
ZonedDateTime issued = ZonedDateTime.of(2026, 1, 15, 10, 30, 0, 0, ZoneId.of("Europe/Madrid"));
Path original = Path.of("output/F-2026-0001.pdf");
Path withMetadata = Path.of("output/F-2026-0001-metadata.pdf");

System.out.println("=== Before");
show(original);
PdfEditor.edit(original, withMetadata, PdfEditor.Mode.INCREMENTAL,
        document -> Metadata.forInvoice(document, invoice, issued));
System.out.println("=== After");
show(withMetadata);
=== Before
  Language: null
  XMP: (none)
=== After
  Info Author         Nebula Distribution Ltd.
  Info CreationDate   D:20260115103000+01'00'
  Info Creator        InvoiceLab
  Info CustomerVatId  J00000000
  Info InvoiceNumber  F-2026-0001
  Info Keywords       invoice; F-2026-0001; J00000000
  Info ModDate        D:20261127182927+01'00'
  Info Producer       InvoiceLab (Apache PDFBox 3.0)
  Info Subject        Invoice F-2026-0001 to Example Hardware Co. for 4.193,94 €
  Info Title          Invoice F-2026-0001
  Info Total          4193.94
  Language: en-GB
  XMP dc:title     Invoice F-2026-0001
  XMP dc:creator   [Nebula Distribution Ltd.]
  XMP pdf:Producer InvoiceLab (Apache PDFBox 3.0)
  XMP xmp:CreateDate 2026-01-15T10:30+01:00[Europe/Madrid]

The invoice generated in module 3 had no metadata at all. (Ideally the generator itself should set it when creating the document; you'll practise this in exercise 3.) If you open the file in a text editor and search for xpacket, you'll see the XMP in plain text:

<rdf:Description rdf:about="">
  <dc:title>
    <rdf:Alt>
      <rdf:li xml:lang="x-default">Invoice F-2026-0001</rdf:li>
    </rdf:Alt>
  </dc:title>
  <dc:creator>
    <rdf:Seq>
      <rdf:li>Nebula Distribution Ltd.</rdf:li>
    </rdf:Seq>
  </dc:creator>
  ...
<rdf:Description xmlns:xmp="http://ns.adobe.com/xap/1.0/" rdf:about="">
  <xmp:CreatorTool>InvoiceLab</xmp:CreatorTool>
  <xmp:CreateDate>2026-01-15T10:30:00+01:00</xmp:CreateDate>

Notice that XMP uses the ISO 8601 date format (2026-01-15T10:30:00+01:00), which differs from Info's (D:20260115103000+01'00'), although they represent the same instant.

Reading a PDF's metadata

For Info, the getters and getMetadataKeys() are all you need. The example's show method walks through every key:

PDDocumentInformation info = document.getDocumentInformation();
for (String key : info.getMetadataKeys()) {
    System.out.printf("  Info %-14s %s%n", key, info.getPropertyStringValue(key));
}

getPropertyStringValue returns the value exactly as it is in the file (that's why the dates appear in D:... format); to get them as a Calendar, use getCreationDate() and getModificationDate().

For XMP you have to read the stream and parse it with DomXmpParser:

/** Reads the document's XMP, or null if it has none. */
public static XMPMetadata readXmp(PDDocument document) throws IOException {
    PDMetadata metadata = document.getDocumentCatalog().getMetadata();
    if (metadata == null) {
        return null;
    }
    try (InputStream input = metadata.exportXMPMetadata()) {
        return new DomXmpParser().parse(input);
    } catch (XmpParsingException e) {
        throw new IOException("Invalid XMP: " + e.getMessage(), e);
    }
}

And then you query each schema:

XMPMetadata xmp = Metadata.readXmp(document);
if (xmp != null && xmp.getDublinCoreSchema() != null) {
    String title = xmp.getDublinCoreSchema().getTitle();           // may throw BadFieldValueException
    List<String> authors = xmp.getDublinCoreSchema().getCreators();
}
  • Any schema may be missing: getDublinCoreSchema(), getAdobePDFSchema() and getXMPBasicSchema() return null if the XMP doesn't include it. Always check for this in third-party documents.
  • getTitle() declares BadFieldValueException because third-party XMP may contain malformed values.
  • DomXmpParser is strict by default and rejects XMP with errors; with setStrictParsing(false) it's more lenient, which is useful when inspecting other people's documents.

Privacy: cleaning metadata before publishing

Metadata travels with the file. A PDF published on the web or sent to a third party may reveal the name of the employee who wrote it (/Author), the internal tool that generated it, working titles ("Hardware quote – DO NOT SEND"), dates or file paths. Before publishing a document it's wise to clean it:

/**
 * Removes metadata that may reveal internal information before a document is published:
 * the information dictionary, the document's and pages' XMP, and private application data.
 * Returns the list of what was removed.
 */
public static List<String> clean(PDDocument document) {
    List<String> removed = new ArrayList<>();
    PDDocumentInformation info = document.getDocumentInformation();
    for (String key : info.getMetadataKeys()) {
        removed.add("Info/" + key);
    }
    document.setDocumentInformation(new PDDocumentInformation());
    PDDocumentCatalog catalog = document.getDocumentCatalog();
    if (catalog.getMetadata() != null) {
        catalog.setMetadata(null);
        removed.add("document XMP");
    }
    if (catalog.getCOSObject().containsKey(COSName.PIECE_INFO)) {
        catalog.getCOSObject().removeItem(COSName.PIECE_INFO);
        removed.add("catalog PieceInfo");
    }
    int number = 0;
    for (PDPage page : document.getPages()) {
        number++;
        for (COSName key : new COSName[] { COSName.METADATA, COSName.PIECE_INFO }) {
            if (page.getCOSObject().containsKey(key)) {
                page.getCOSObject().removeItem(key);
                removed.add(key.getName() + " of page " + number);
            }
        }
    }
    return removed;
}
  • Replacing the information dictionary with a new, empty one removes every key in one go, including the custom ones.
  • setMetadata(null) removes the document's XMP. Pages can also have their own /Metadata.
  • /PieceInfo is a dictionary in which some applications (design programs, for example) store private editing data, sometimes very bulky and revealing.
  • The method returns what it removed: in a publishing process it's worth logging this.

And now the most important part. The example cleans the invoice with metadata in both save modes and searches for the string InvoiceNumber in the bytes of the resulting file:

for (PdfEditor.Mode mode : PdfEditor.Mode.values()) {
    Path clean = Path.of("output/F-2026-0001-clean-" + mode.name().toLowerCase() + ".pdf");
    PdfEditor.edit(withMetadata, clean, mode, document -> {
        List<String> removed = Metadata.clean(document);
        System.out.println("Removed (" + mode + "): " + removed);
    });
    String bytes = new String(Files.readAllBytes(clean), StandardCharsets.ISO_8859_1);
    System.out.println("  Is 'InvoiceNumber' still in the file? " + bytes.contains("InvoiceNumber"));
}
Removed (FULL): [Info/Author, Info/CreationDate, Info/Creator, Info/CustomerVatId, Info/InvoiceNumber, Info/Keywords, Info/ModDate, Info/Producer, Info/Subject, Info/Title, Info/Total, document XMP]
  Is 'InvoiceNumber' still in the file? false
Removed (INCREMENTAL): [Info/Author, Info/CreationDate, Info/Creator, Info/CustomerVatId, Info/InvoiceNumber, Info/Keywords, Info/ModDate, Info/Producer, Info/Subject, Info/Title, Info/Total, document XMP]
  Is 'InvoiceNumber' still in the file? true

With the incremental save, the "removed" metadata is still in the previous revision, perfectly readable with a text editor: the update only says that the current document no longer uses it. It's the flip side of what you learned in 04-01: what is an advantage for auditing is a risk for privacy. A privacy cleanup must always be saved in full mode.

And even so, metadata isn't the only place where information hides. Review what you've seen in this module:

Where Lesson How to remove it
Previous revisions (incremental save) 04-01 Full save
Content outside the CropBox 04-03 Remove the content (redaction), don't crop
Hidden layers 04-05 Remove the optional content
Information dictionary and XMP This one Metadata.clean + full save
Annotations and attached files 06-05 Remove them from the pages and from the catalog
Form fields Module 5 Flatten or remove

Common Mistakes and Tips

  • Updating Info and forgetting XMP (or vice versa). The document ends up out of sync and won't pass PDF/A validation. Always regenerate the XMP with syncXmp after touching Info.
  • Mixing up Creator, CreatorTool and Author. /Author → dc:creator; /Creator → xmp:CreatorTool. Go over the mapping table again.
  • Dates without a time zone. A Calendar created without a zone uses the server's, which may be UTC. Create dates from a ZonedDateTime with an explicit zone.
  • Forgetting the xmpbox dependency. The org.apache.xmpbox.* classes don't come with pdfbox. Add it with the same version (${pdfbox.version}).
  • Compressing or hand-editing the XMP. Leave it uncompressed (importXMPMetadata does that) and don't modify it with string operations: use xmpbox.
  • Cleaning in incremental mode. The data is still in the file. For privacy, a full save.
  • Tip: set the metadata in the generator (in BaseGenerator, before saving) so that every invoice comes out complete from the start; keep after-the-fact editing for documents that have already been issued or that come from third parties.

Exercises

Exercise 1. Write static void audit(Path folder), which walks through the PDFs in a folder and reports for each one whether its title is OK (Info and XMP match), OUT OF SYNC (they don't match) or NO TITLE (neither has one). A PDF that can't be opened mustn't stop the audit. Try it by creating a copy of F-2026-0001-metadata.pdf in which you change only the Info title.

Exercise 2. Add metadata to the batch from lesson 04-04: title "Invoice batch 2026-01", author, InvoiceLab creator and producer, current creation date, synced XMP, English as the language and an opening layout suitable for a document prepared for double-sided printing.

Exercise 3. Modify BaseGenerator (lesson 03-04) so that every generated document comes out with creator, producer, creation date, language and XMP, by adding a protected String title(T data) method that each concrete generator implements (for example, "Invoice F-2026-0001" or "Delivery note A-2026-0001").

Solutions

Solution 1.

public static void audit(Path folder) throws IOException {
    List<Path> pdfs;
    try (Stream<Path> files = Files.list(folder)) {
        pdfs = files.filter(p -> p.toString().endsWith(".pdf")).sorted().toList();
    }
    for (Path pdf : pdfs) {
        try (PDDocument document = Loader.loadPDF(pdf.toFile())) {
            String infoTitle = document.getDocumentInformation().getTitle();
            XMPMetadata xmp = Metadata.readXmp(document);
            String xmpTitle = null;
            if (xmp != null && xmp.getDublinCoreSchema() != null) {
                try {
                    xmpTitle = xmp.getDublinCoreSchema().getTitle();
                } catch (BadFieldValueException e) {
                    xmpTitle = "(invalid)";
                }
            }
            String status = infoTitle == null && xmpTitle == null ? "NO TITLE"
                    : Objects.equals(infoTitle, xmpTitle) ? "OK" : "OUT OF SYNC";
            System.out.printf("%-32s %-15s Info=%s | XMP=%s%n", pdf.getFileName(), status, infoTitle, xmpTitle);
        } catch (IOException e) {
            System.out.printf("%-32s ERROR %s%n", pdf.getFileName(), e.getMessage());
        }
    }
}

To create the out-of-sync case:

PdfEditor.edit(Path.of("output/F-2026-0001-metadata.pdf"), Path.of("output/F-2026-0001-unsync.pdf"),
        PdfEditor.Mode.FULL, d -> d.getDocumentInformation().setTitle("Invoice F-2026-0001 (corrected)"));
F-2026-0001-metadata.pdf         OK              Info=Invoice F-2026-0001 | XMP=Invoice F-2026-0001
F-2026-0001-unsync.pdf           OUT OF SYNC     Info=Invoice F-2026-0001 (corrected) | XMP=Invoice F-2026-0001
F-2026-0001.pdf                  NO TITLE        Info=null | XMP=null

Objects.equals compares correctly even if one of the two is null. The try/catch is inside the loop, so a damaged file is logged as ERROR and the audit carries on with the next one. This is exactly the kind of error that syncXmp prevents.

Solution 2.

PdfEditor.edit(Path.of("output/batch-2026-01.pdf"), Path.of("output/batch-2026-01.pdf"),
        PdfEditor.Mode.FULL, document -> {
            PDDocumentInformation info = document.getDocumentInformation();
            info.setTitle("Invoice batch 2026-01");
            info.setAuthor("Nebula Distribution Ltd.");
            info.setCreator(Metadata.CREATOR);
            info.setProducer(Metadata.PRODUCER);
            info.setCreationDate(GregorianCalendar.from(ZonedDateTime.now(ZoneId.of("Europe/Madrid"))));
            Metadata.syncXmp(document);
            PDDocumentCatalog catalog = document.getDocumentCatalog();
            catalog.setLanguage("en-GB");
            catalog.setPageLayout(PageLayout.TWO_PAGE_RIGHT);
        });

TWO_PAGE_RIGHT shows the pages two at a time with the odd pages on the right: the cover alone on the right and then each pair (2-3, 4-5…) like an open book. Since the batch starts each invoice on an odd page, the reader sees it just as it looks on paper printed double-sided. Source and target are the same file: PdfEditor allows this thanks to the temporary file and the rename (lesson 04-01).

Solution 3.

In BaseGenerator.generate, right before document.save(output):

PageFooter.numberPages(document, ctx.fonts(), footerText(data));   // 4) second pass
PDDocumentInformation info = document.getDocumentInformation();     // 5) metadata
info.setTitle(title(data));
info.setCreator(Metadata.CREATOR);
info.setProducer(Metadata.PRODUCER);
info.setCreationDate(GregorianCalendar.from(ZonedDateTime.now(ZoneId.of("Europe/Madrid"))));
Metadata.syncXmp(document);
document.getDocumentCatalog().setLanguage("en-GB");
ByteArrayOutputStream output = new ByteArrayOutputStream();
document.save(output);                                             // 6) to memory

and the new abstract method:

/** Document title for its metadata ("Invoice F-2026-0001"...). */
protected abstract String title(T data);

In InvoiceGenerator: return "Invoice " + invoice.number();; in DeliveryNoteGenerator: return "Delivery note " + deliveryNote.number();; in BatchCoverGenerator: return "Invoice batch " + batch.period();. Because it's abstract, the compiler forces every generator to implement it: no new document will ever come out without a title. Note the direction of the dependencies: generator now uses editing.Metadata. If you'd rather keep editing as the upper layer, move Metadata (or at least syncXmp) to the pdf package, which holds the utilities and is already a dependency of both.

Conclusion

With this lesson you complete module 4. You know how to read and write the document information dictionary (PDDocumentInformation, with its Calendar dates and custom keys such as InvoiceNumber) and XMP metadata with xmpbox (XMPMetadata, DublinCoreSchema, AdobePDFSchema, XMPBasicSchema, XmpSerializer and PDMetadata), and you understand why InvoiceLab keeps them in sync by treating Info as the source of truth, something PDF/A will require in module 8. You've declared the document's language, configured the viewer preferences and the opening mode, and confirmed that cleaning metadata is only effective if you save in full mode. Throughout the module you've built the com.invoicelab.editing package: PdfEditor for safe editing in full or incremental mode, Stamper for stamps and watermarks, Pages for page manipulation, InvoiceBatches and Splitting for merging and splitting documents, Layers for overlays, optional content and imposition, and Metadata.

So far, every PDF we've handled has been a document to read. In module 5 we'll work with PDFs that get filled in: AcroForm forms. We'll start with a real case at Nebula Distribution, the customer registration form that new customers send back as a fillable PDF, to understand how its fields are structured before reading them, filling them in and creating them from InvoiceLab.

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