In the previous lesson we generated a PDF, but we treated it as a black box. In this lesson we are going to open it up. You will see that, deep down, a PDF is a fairly readable file: a collection of objects (numbers, names, dictionaries, arrays…) linked to one another, plus an index that lets you find them quickly. Understanding this anatomy is what separates someone who "copies PDFBox examples" from someone who knows why a PDF comes out blank, why a font doesn't show up, or how to read a property that the high-level API doesn't expose. What's more, PDFBox is literally built on these concepts: its COS layer is an exact mirror of the format's objects.
Contents
- Physical file structure: header, body, xref, trailer and
%%EOF - Indirect objects and references
- PDF object types and their COS classes in PDFBox
- Logical structure: Catalog → Pages → Page → Resources and Contents
- A minimal PDF written by hand, line by line
- The two layers of PDFBox: the PD model and the COS layer
- Walking through a page dictionary in code
- When to drop down to the COS layer
Physical file structure
A classic PDF has four parts, always in this order:
flowchart TB
H["Header<br/>%PDF-1.7"] --> B["Body<br/>objects 1 0 obj … endobj"]
B --> X["Cross-reference table (xref)<br/>byte position of each object"]
X --> T["Trailer<br/><< /Size … /Root … >><br/>startxref + xref position"]
T --> E["%%EOF"]
| Part | What it contains | What it is for |
|---|---|---|
| Header | %PDF-1.7 (and often a second comment line with non-ASCII bytes) |
Identifies the file as a PDF and gives its version. The second line tells file-transfer tools that this is a binary file |
| Body | The document's objects: pages, fonts, images, content… | It is the document itself |
| xref table | One line per object with its byte offset from the start of the file | Lets a reader jump straight to any object without reading the whole file |
| Trailer | A dictionary with /Size (number of entries) and /Root (the root object), followed by startxref with the position of the xref table |
It is the entry point: readers start at the end of the file |
%%EOF |
End-of-file marker | Marks the end of the last revision |
A crucial detail: PDF readers read the file starting from the end. They look for %%EOF, step back to startxref, read the position of the xref table, jump to it and, from the trailer, locate the root object. This is why:
- A truncated PDF (an incomplete download) usually throws errors: its ending is missing.
- A new revision can be appended to the end of the file without touching what came before (this is incremental saving, which is key for digital signatures; we will cover it in module 4).
A note on modern PDFs: since PDF 1.5, the xref table can be stored compressed inside an xref stream, and many objects can be grouped into object streams. PDFBox 3 saves this way by default, which is why a PDF generated with PDFBox looks largely binary when you open it in a text editor. In lesson 01-05 you will learn how to generate uncompressed versions for debugging.
Indirect objects and references
In the body, every object "with a name of its own" is declared as an indirect object:
4is the object number.0is the generation number (almost always 0; it only increases when the number of a deleted object is reused).- Between
objandendobjcomes the object's value: here, a dictionary describing a font.
From anywhere else in the document you can point to that object with an indirect reference:
This reads as "object 4, generation 0". The R stands for reference. It is the equivalent of a pointer: it lets several pages share the same font or the same image without duplicating it.
PDF object types and their COS classes in PDFBox
The PDF format has only eight basic object types (plus the null object and references). PDFBox represents them in the org.apache.pdfbox.cos package (COS stands for Carousel Object System, PDF's original internal name at Adobe). All the classes extend COSBase.
| PDF type | Syntax in the file | PDFBox class | Example use |
|---|---|---|---|
| Boolean | true, false |
COSBoolean |
Flags such as /NeedAppearances true |
| Integer | 42, -7 |
COSInteger |
/Count 3, /Length 47 |
| Real | 3.14, -0.5, .25 |
COSFloat |
Coordinates such as 595.28 |
| String | (Hello) or <48656C6C6F> (hexadecimal) |
COSString |
Titles, text, identifiers |
| Name | /Type, /Helvetica |
COSName |
Dictionary keys and "enumerated" values |
| Array | [0 0 595 842] |
COSArray |
Lists: /Kids, /MediaBox |
| Dictionary | << /Key value … >> |
COSDictionary |
The main structure: pages, fonts, catalog… |
| Stream | dictionary + stream … endstream |
COSStream (extends COSDictionary) |
Page content, images, embedded fonts |
| Null | null |
COSNull |
Missing value |
| Indirect reference | 4 0 R |
COSObject |
Points to another object |
Some important remarks for beginners:
- Name ≠ string.
/Helveticais a name (an identifier, like anenumconstant), whereas(Helvetica)is a text string. A dictionary key is always a name. Mixing them up is a classic mistake when working at a low level. COSIntegerandCOSFloatextendCOSNumber, which is useful when you don't know whether you'll get an integer or a real (for example, a/MediaBoxmay contain both).- A stream is a dictionary (with at least
/Length) followed by an arbitrary sequence of bytes, usually compressed (/Filter /FlateDecode). It is the only type that can hold large amounts of binary data. COSNamedefines constants for the common names:COSName.TYPE,COSName.PAGES,COSName.MEDIA_BOX,COSName.RESOURCES,COSName.FONT,COSName.CONTENTS… Use them instead of creating names by hand whenever they exist.
Logical structure: Catalog → Pages → Page → Resources and Contents
The objects are organized in a tree. The trailer points to the catalog (/Root), and from there you can reach everything else:
flowchart TB
TR["Trailer<br/>/Root"] --> CAT["Catalog<br/>/Type /Catalog"]
CAT --> PAGES["Pages (page tree)<br/>/Type /Pages · /Count · /Kids"]
CAT -.-> OTHERS["Others: /AcroForm, /Outlines,<br/>/Metadata, /Names…"]
PAGES --> P1["Page 1<br/>/Type /Page · /MediaBox · /Parent"]
PAGES --> P2["Page 2 …"]
P1 --> RES["Resources<br/>/Font · /XObject · /ExtGState…"]
P1 --> CONT["Contents (stream)<br/>drawing operators"]
RES --> F1["Font /F1<br/>Helvetica"]
RES --> IM1["XObject /Im1<br/>logo image"]
| Object | Main keys | What it represents |
|---|---|---|
| Catalog | /Type /Catalog, /Pages |
The root of the document. It can also point to forms (/AcroForm, module 5), bookmarks (/Outlines, module 6) or metadata (/Metadata, module 4) |
| Pages | /Type /Pages, /Kids, /Count |
A node in the page tree. /Kids lists its children and /Count the total number of pages beneath it. Large documents have several levels |
| Page | /Type /Page, /Parent, /MediaBox, /Resources, /Contents |
A page. /MediaBox gives its size in points |
| Resources | /Font, /XObject, /ExtGState, /ColorSpace… |
The "ingredients" the page uses, each with a short local name (/F1, /Im1) |
| Contents | Stream | The drawing instructions: "use font /F1, move to…, write…" |
The relationship between Resources and Contents is the key to understanding why a PDF "comes out blank" or throws errors: the content says /F1 24 Tf ("use font F1 at 24 points"), and the viewer looks up F1 in the page's resources. If it can't find it, the text isn't painted. PDFBox manages this link for you when you use its high-level API, but it's worth knowing that it exists.
A minimal PDF written by hand
This is a complete, valid one-page PDF that displays "Hello, InvoiceLab". You can copy it into a file called output/minimal-by-hand.pdf with a text editor (save it with LF line endings, Unix style, so that the offsets in the xref table are exact):
%PDF-1.7
1 0 obj
<< /Type /Catalog /Pages 2 0 R >>
endobj
2 0 obj
<< /Type /Pages /Kids [3 0 R] /Count 1 >>
endobj
3 0 obj
<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842]
/Resources << /Font << /F1 4 0 R >> >>
/Contents 5 0 R >>
endobj
4 0 obj
<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>
endobj
5 0 obj
<< /Length 48 >>
stream
BT /F1 24 Tf 72 770 Td (Hello, InvoiceLab) Tj ET
endstream
endobj
xref
0 6
0000000000 65535 f
0000000009 00000 n
0000000058 00000 n
0000000115 00000 n
0000000247 00000 n
0000000317 00000 n
trailer
<< /Size 6 /Root 1 0 R >>
startxref
415
%%EOFLet's go through it line by line:
%PDF-1.7: the header. It indicates version 1.7 of the format.- Object 1, the catalog:
/Type /Catalogidentifies it, and/Pages 2 0 Rpoints to the page tree (object 2). - Object 2, the page tree:
/Kids [3 0 R]is an array with a single page (object 3), and/Count 1says there is one page in total. - Object 3, the page:
/Parent 2 0 Rpoints back to its parent (the page tree can be navigated in both directions)./MediaBox [0 0 595 842]defines the page rectangle: bottom-left corner (0, 0) and top-right corner (595, 842). In typographic points (1/72 of an inch), that is an A4 page./Resources << /Font << /F1 4 0 R >> >>is a direct dictionary (not an indirect object) that says: "on this page, the nameF1means the font in object 4"./Contents 5 0 Rpoints to the stream with the drawing instructions.
- Object 4, the font: a standard Type1 font, Helvetica. The 14 standard fonts don't need to be embedded; the viewer supplies them (we will study this in module 2).
- Object 5, the content: an uncompressed 48-byte stream (
/Length 48). Its operators, which we will look at in detail in lesson 02-02, mean:BT: begin a text block (Begin Text)./F1 24 Tf: use fontF1at 24 points (Text font).72 770 Td: move to x = 72, y = 770, measured from the bottom-left corner (Text displacement).(Hello, InvoiceLab) Tj: write the string (Text show).ET: end the text block (End Text).
xref: the cross-reference table.0 6indicates that the table starts at object 0 and has 6 entries.- The first line (
0000000000 65535 f) is the head of the free-object list (f= free); it is always present. - Each subsequent line gives an object's byte offset, its generation and
n(in use). For example, object 1 starts at byte 9, right after%PDF-1.7and its line break (8 + 1 bytes). - Each entry is exactly 20 bytes long, including the trailing space before the line break.
trailer:/Size 6(the number of xref entries) and/Root 1 0 R(the catalog).startxref 415: the xref table starts at byte 415.%%EOF: end of file.
Open it in your viewer: you will see "Hello, InvoiceLab" at the top of an A4 page. If you get an offset wrong, many viewers (and PDFBox) "repair" the file by rebuilding the xref on the fly; that is handy, but don't take it as an excuse to generate incorrect files.
This is not how we will generate PDFs. This exercise is purely educational. Writing PDFs by hand is error-prone; that's what PDFBox is for. But from now on, when you see
COSDictionaryorCOSName.RESOURCESin code, you will know exactly what it corresponds to.
The two layers of PDFBox: the PD model and the COS layer
PDFBox offers two levels of abstraction over the same information:
flowchart LR
subgraph PD["PD layer (org.apache.pdfbox.pdmodel)"]
D[PDDocument] --> C[PDDocumentCatalog]
C --> PT[PDPageTree]
PT --> P[PDPage]
P --> R[PDResources]
end
subgraph COS["COS layer (org.apache.pdfbox.cos)"]
CD[COSDocument] --> CC["COSDictionary /Catalog"]
CC --> CPS["COSDictionary /Pages"]
CPS --> CP["COSDictionary /Page"]
CP --> CR["COSDictionary /Resources"]
end
P -. getCOSObject .-> CP
D -. getDocument .-> CD
C -. getCOSObject .-> CC
| Aspect | PD layer (Portable Document) | COS layer |
|---|---|---|
| Package | org.apache.pdfbox.pdmodel and subpackages |
org.apache.pdfbox.cos |
| Typical classes | PDDocument, PDPage, PDResources, PDRectangle, PDFont |
COSDictionary, COSArray, COSName, COSStream |
| Level | High: meaningful methods (getMediaBox(), getNumberOfPages()) |
Low: keys and values exactly as they appear in the file |
| Safety | Validates types and applies defaults and inheritance | Lets you write anything, even an invalid PDF |
| Recommended use | 95% of the time | Special cases and debugging |
The important thing is that they are not two copies of the data: PD objects are wrappers around COS objects. PDPage contains a COSDictionary, and everything you do with PDPage turns into changes to that dictionary. You can move from one to the other at any time:
| From | Method | You get |
|---|---|---|
PDDocument |
getDocument() |
COSDocument (the low-level document) |
PDDocumentCatalog |
getCOSObject() |
The catalog's COSDictionary |
PDPage |
getCOSObject() |
The page's COSDictionary |
PDResources |
getCOSObject() |
The resources COSDictionary |
Page COSDictionary |
new PDPage(dict) |
A PDPage wrapping that dictionary |
Almost every class in the PD layer implements the COSObjectable interface, which is precisely what defines getCOSObject().
Walking through a page dictionary in code
Let's load the hand-written PDF and print what its first page dictionary contains. Create com.invoicelab.examples.InspectPage:
package com.invoicelab.examples;
import java.io.File;
import java.io.IOException;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.cos.COSArray;
import org.apache.pdfbox.cos.COSBase;
import org.apache.pdfbox.cos.COSDictionary;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.cos.COSObject;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
/**
* Shows the COS structure of the first page of a PDF.
* Usage: InspectPage [path.pdf] (defaults to output/minimal-by-hand.pdf)
*/
public class InspectPage {
public static void main(String[] args) throws IOException {
String path = args.length > 0 ? args[0] : "output/minimal-by-hand.pdf";
try (PDDocument document = Loader.loadPDF(new File(path))) {
// 1. PD layer: the first page (index 0)
PDPage page = document.getPage(0);
// 2. Drop down to the COS layer: the /Page dictionary
COSDictionary pageDict = page.getCOSObject();
System.out.println("Keys in the page 1 dictionary:");
for (COSName key : pageDict.keySet()) {
COSBase rawValue = pageDict.getItem(key); // as-is (may be a reference)
COSBase value = pageDict.getDictionaryObject(key); // resolved (follows the reference)
String indirect = (rawValue instanceof COSObject ref)
? " (indirect reference " + ref.getKey() + ")"
: "";
System.out.printf(" /%-10s -> %s%s%n",
key.getName(), value.getClass().getSimpleName(), indirect);
}
// 3. Read specific values with COSDictionary's typed methods
COSArray mediaBox = pageDict.getCOSArray(COSName.MEDIA_BOX);
float[] box = mediaBox.toFloatArray();
System.out.printf("MediaBox: width=%.2f height=%.2f%n", box[2] - box[0], box[3] - box[1]);
// 4. Navigate Resources -> Font -> each font
COSDictionary resources = pageDict.getCOSDictionary(COSName.RESOURCES);
COSDictionary fonts = resources.getCOSDictionary(COSName.FONT);
for (COSName name : fonts.keySet()) {
COSDictionary font = (COSDictionary) fonts.getDictionaryObject(name);
System.out.println("Font /" + name.getName() + " = "
+ font.getNameAsString(COSName.BASE_FONT));
}
}
}
}Output when run against output/minimal-by-hand.pdf:
Keys in the page 1 dictionary:
/Type -> COSName
/Parent -> COSDictionary (indirect reference 2 0 R)
/MediaBox -> COSArray
/Resources -> COSDictionary
/Contents -> COSStream (indirect reference 5 0 R)
MediaBox: width=595.00 height=842.00
Font /F1 = HelveticaKey points in the code:
Loader.loadPDF(File)is how you load a PDF in PDFBox 3 (in lesson 01-04 we will look at all its variants). Here we only need it to have something to inspect.keySet()returns the dictionary's keys (COSName).key.getName()gives the name without the slash.getItemversusgetDictionaryObject: this is the most important distinction in the example.getItem(key)returns the raw value. If the file says5 0 R, you get aCOSObject(the reference).getDictionaryObject(key)resolves the reference and returns the actual object (COSStream). This is the one you'll want almost every time.
- Notice that
/Resourcesappears as aCOSDictionarywithout a reference: in our PDF it is written directly inside the page (a direct object). In other PDFs it may be indirect; withgetDictionaryObjectit makes no difference. getCOSArray,getCOSDictionaryandgetNameAsStringare shortcuts that resolve references and check the type: they returnnullif the key doesn't exist or has a different type. That way you avoid aClassCastException.ref.getKey()returns aCOSObjectKey, whose text representation is"2 0 R".
Try running it on output/check.pdf too (the PDF from the previous lesson) or on any PDF you have to hand: you will see that real-world PDFs usually have more keys (/Rotate, /CropBox, /Annots, /Group…).
When to drop down to the COS layer
The general rule is: use the PD layer whenever you can. It validates data, applies inheritance (for example, a page can inherit /MediaBox or /Resources from its parent /Pages node, and PDPage.getMediaBox() takes that into account, whereas reading the key from the COSDictionary does not) and stops you from producing an invalid PDF.
Only drop down to COS when you genuinely need to:
| Situation | Example |
|---|---|
| The PD API doesn't expose a property | Unusual or vendor-specific keys |
| Debugging or diagnosing | Seeing what's actually in a page that "comes out blank" |
| Storing your own data in the document | An internal InvoiceLab reference in the page dictionary |
| Reading "odd" or damaged PDFs | Values of an unexpected type that the PD layer rejects |
| Advanced features | Incremental saving, signatures, structures we will see in later modules |
For example, this is how we would store and read a private key holding the invoice number on a page:
COSName refKey = COSName.getPDFName("InvoiceLabRef"); // creates (or reuses) the name /InvoiceLabRef
page.getCOSObject().setString(refKey, "F-2026-0001"); // stores it as a COSString
String ref = page.getCOSObject().getString(refKey); // "F-2026-0001", or null if it doesn't existViewers ignore keys they don't recognize, so this doesn't affect how the page looks. Even so, there are better-suited mechanisms for document metadata (document information and XMP, in lesson 04-06); use this sparingly.
Common Mistakes and Tips
- Using
getItemwhen you meantgetDictionaryObject. You get aCOSObjectinstead of the actual dictionary or stream, and the cast fails with aClassCastException. - Confusing names and strings.
COSName.getPDFName("Helvetica")is not the same asnew COSString("Helvetica"). Keys and "enumerated" values (/Type /Page) are names. - Reading
/MediaBoxor/Resourcesonly from the page dictionary. They can be inherited from the parent node; usePDPage.getMediaBox()andPDPage.getResources(), which resolve inheritance. - Modifying the COS layer without understanding the specification. It's easy to create a PDF that PDFBox saves without complaint but Acrobat rejects. If you touch COS, check the result in several viewers and with PDFDebugger (lesson 01-05).
- Editing PDFs by hand and breaking the offsets. If you add a character inside an object, every subsequent offset changes. When experimenting, let PDFBox rewrite the file.
- Tip: when you're not sure which key to use, look for the constant in
COSNamefrom your IDE (typeCOSName.and let autocomplete show you the list); it's a good way to discover the format's vocabulary.
Exercises
Exercise 1. Looking at the hand-written PDF, answer without running anything:
a) What would happen if, in object 3, you changed /F1 4 0 R to /F2 4 0 R without touching the content stream?
b) What does /Count 1 represent, and what value should it have if you added a second page?
c) Why does the first entry in the xref table have generation number 65535?
Exercise 2. Write an InspectCatalog class that loads a PDF and, using only the COS layer starting from document.getDocumentCatalog().getCOSObject(), prints all the catalog's keys and, by following /Pages, the value of /Count.
Exercise 3. Modify InspectPage so that, instead of looking only at the first page, it goes through all the pages of the document and prints, for each one, its number and the number of fonts declared in its resources (0 if there are none). Hint: PDDocument.getPages() is iterable, and PDPage.getResources() is the safe way to get the resources.
Solutions
Solution 1.
a) The content would still say /F1 24 Tf, but F1 would no longer exist in the resources. The viewer wouldn't find the font: depending on the viewer, the text would not be displayed or an error would be shown. It's an example of why Resources and Contents must stay in sync.
b) It is the total number of pages (leaves of the tree) under that /Pages node. With a second page, /Kids would have two references and /Count would be 2.
c) Entry 0 is special: it is the head of the free-object list and is never used for a real object. By convention it carries the maximum generation, 65535, so that this object number is never reused.
Solution 2.
package com.invoicelab.examples;
import java.io.File;
import java.io.IOException;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.cos.COSDictionary;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.PDDocument;
public class InspectCatalog {
public static void main(String[] args) throws IOException {
String path = args.length > 0 ? args[0] : "output/minimal-by-hand.pdf";
try (PDDocument document = Loader.loadPDF(new File(path))) {
COSDictionary catalog = document.getDocumentCatalog().getCOSObject();
System.out.println("Catalog keys:");
for (COSName key : catalog.keySet()) {
System.out.println(" /" + key.getName() + " -> "
+ catalog.getDictionaryObject(key).getClass().getSimpleName());
}
COSDictionary pages = catalog.getCOSDictionary(COSName.PAGES);
System.out.println("Page count according to /Count: " + pages.getInt(COSName.COUNT));
}
}
}getInt(COSName) returns -1 if the key doesn't exist. Compare the result with document.getNumberOfPages(): they should match.
Solution 3.
int number = 1;
for (PDPage page : document.getPages()) {
PDResources resources = page.getResources(); // resolves page tree inheritance
int fontCount = 0;
if (resources != null) {
for (COSName name : resources.getFontNames()) {
fontCount++;
}
}
System.out.println("Page " + number + ": " + fontCount + " font(s)");
number++;
}You need to import org.apache.pdfbox.pdmodel.PDResources. getFontNames() returns an Iterable<COSName> with the fonts' local names (F1, F2…). Common mistake: using pageDict.getCOSDictionary(COSName.RESOURCES) and getting null on PDFs whose pages inherit their resources from the parent node.
Conclusion
You now know what's inside a PDF: a header, a body of indirect objects, an xref table with their positions and a trailer pointing to the catalog, all read from the end of the file. You know there are only a handful of object types (booleans, numbers, strings, names, arrays, dictionaries, streams and null) and that PDFBox represents them with the COS* classes. You have also seen the logical tree Catalog → Pages → Page → Resources/Contents and the relationship between the PD layer (high level, the one you'll use almost always) and the COS layer (low level, for special cases and debugging).
With this foundation, in the next lesson we will stop writing PDFs by hand and use the PDFBox API to create, save and load documents properly: the PDDocument lifecycle, our first "Hello, InvoiceLab" generated from code, and a PdfInfo utility for inspecting any PDF.
PDF Generation and Editing with Apache PDFBox
Module 1: PDF and PDFBox Fundamentals
- The PDF Format and Apache PDFBox
- Setting Up the Project with PDFBox 3
- Anatomy of a PDF: COS Objects, Pages and Resources
- Your First PDF: Creating, Saving and Loading Documents
- Debugging Tools: PDFDebugger and the Command Line
Module 2: Generating Content
- Pages and the Coordinate System
- Writing Text with PDPageContentStream and Standard Fonts
- Embedded TrueType Fonts and Unicode
- Text Layout: Measuring, Aligning and Wrapping Lines
- Vector Graphics: Lines, Shapes and Colours
- Inserting Images
Module 3: Business Documents
- Building Tables from Scratch
- Multi-Page Documents: Pagination, Headers and Footers
- Barcodes and QR Codes
- Designing a Reusable Document Generator
- Project: the Complete Invoice
Module 4: Editing Existing PDFs
- Load, Modify and Save: Full and Incremental Saves
- Adding Content to Existing Pages: Stamps and Watermarks
- Page Manipulation: Inserting, Removing, Rotating and Reordering
- Merging and Splitting Documents
- Overlays, Layers and Optional Content
- Document Metadata: Info and XMP
Module 5: AcroForm Forms
- Introduction to AcroForm Forms
- Reading and Filling In Forms
- Creating Forms Programmatically
- Form Appearances and Flattening
Module 6: Extraction and Analysis
- Extracting Text with PDFTextStripper
- Area-Based Extraction and Text Positions
- Extracting Images and Resources
- Rendering Pages to Images
- Bookmarks, Links and Annotations
Module 7: Security and Digital Signatures
- Encryption and Permissions
- Digital Signatures: Concepts and PDF Structure
- Signing Documents with PDFBox and Bouncy Castle
- Verifying Signatures and Visible Signatures
