How to Work with the Pdf Object Model in Java

How to Work with the Pdf Object Model in Java

Access the Document Catalog

The PDF catalog is the root of the document’s object tree and is represented as a PdfDictionary. Access it via Document.getCatalog() to inspect or modify document-level properties:

try (Document doc = new Document("input.pdf")) {
    PdfDictionary catalog = doc.getCatalog();
    // Inspect catalog entries
}

Work with PdfDictionary

PdfDictionary is the fundamental key-value container in this low-level PDF object model. Use PdfName.of() to create name keys and store values of any Pdf object type:

PdfDictionary dict = new PdfDictionary();
dict.set(PdfName.of("Title"), new PdfString("My Document"));
PdfString title = (PdfString) dict.get(PdfName.of("Title"));
System.out.println(title.getString());

Work with PdfArray

PdfArray is the ordered sequence type in this object model. Elements are zero-indexed and can hold any mix of Pdf object types. Retrieve values and cast to the appropriate type:

PdfArray array = new PdfArray();
array.add(PdfInteger.valueOf(100));
array.add(PdfInteger.valueOf(200));
array.add(PdfInteger.valueOf(300));
System.out.println("Array length: " + array.size());
int first = ((PdfInteger) array.get(0)).intValue(); // 100

Access the Trailer Dictionary

The PDF trailer dictionary contains the cross-reference table location and references to the document catalog (/Root) and document information dictionary (/Info):

try (Document doc = new Document("input.pdf")) {
    PdfDictionary trailer = doc.getTrailer();
    // Trailer contains /Root, /Info, /Encrypt entries
}

Named Numbers Tree

The PDF spec’s underlying object model (what ISO 32000-1 calls the COS layer) exposes the PDF name tree structure used for number trees such as the parent tree for structure elements. PdfDictionary and PdfArray are used to traverse the Nums arrays (the PDF spec’s own name for this construct, ISO 32000-1 §7.9.7 — not a Java symbol) in the number tree nodes. This is the lowest-level API for working with the logical structure of a tagged PDF document.

See Also

 English