Cross-reference tables, xref streams and incremental updates
The cross-reference table is the one part of a PDF with a fixed, random-access layout, and everything else about how a reader opens a file follows from it. This page covers the classic text table, the trailer that points to it, the binary cross-reference stream that PDF 1.5 added, the object streams that go with it, and incremental updates, the mechanism by which editing a PDF appends a new revision instead of rewriting the file. The examples are real files you can download and take apart.
The classic table#
A cross-reference section starts with the keyword xref on its own line, followed by one or more subsections. Each subsection begins with two integers, the first object number it covers and the number of entries, and then exactly that many 20-byte entries (ISO 32000-1 §7.5.4). An in-use entry is a 10-digit byte offset, a space, a 5-digit generation number, a space, the letter n, and a two-character end of line (space-CR, space-LF or CR-LF). A free entry has the same shape with f, and its first field is not an offset but the object number of the next free entry, forming a linked list whose head is object 0 and whose tail points back to 0.
xref
0 6
0000000003 65535 f % object 0: free, next free object is 3
0000000017 00000 n % object 1 at byte 17
0000000081 00000 n
0000000000 00007 f % object 3 was deleted; a new object 3 would be generation 7
0000000331 00000 n
0000000409 00000 nThe fixed width is the point. To find object 4 a reader computes the position of its entry arithmetically and seeks there; it never has to parse the entries before it. The price is fragility: offsets are absolute byte positions from the start of the file, so inserting or removing a single byte anywhere earlier invalidates every entry after it.
Generation numbers exist so that an object number can be reused safely. When an object is deleted its entry becomes free and its generation is incremented; the next object created with that number carries the new generation, and old references such as 3 0 R no longer match 3 7 obj. The maximum is 65,535, after which the number is never reused. In practice almost no software deletes and reuses numbers, so nearly every file you meet has generation 0 throughout.
Across all sections of a file the table must contain an entry for every object number from 0 up to /Size minus one, even for numbers that were never used, which is why writers emit free entries for gaps.
The trailer#
After the table comes the keyword trailer and a dictionary (Table 15), then startxref, the byte offset of the xref keyword, and %%EOF.
| Key | Required | Meaning |
|---|---|---|
/Size | yes | One greater than the highest object number in the file, counting every section. Must be a direct integer. |
/Root | yes | Reference to the document catalog. |
/Prev | when updated | Byte offset of the previous cross-reference section; present only in files with more than one section. |
/Info | no | Reference to the document information dictionary (title, author, dates); see metadata. |
/ID | if encrypted | Array of two byte strings identifying the file; the first is fixed at creation, the second changes on each save. Must be direct and unencrypted. |
/Encrypt | if encrypted | The encryption dictionary; see encryption. |
/XRefStm | hybrid files only | Byte offset of a cross-reference stream holding entries that pre-1.5 readers cannot see (Table 19). |
A reader locates all of this by reading from the end of the file. The specification says the last line must contain only the %%EOF marker (§7.5.5); in practice readers, following Adobe's old implementation notes for Acrobat, search the final 1024 bytes for startxref, which is why trailing junk after %%EOF rarely stops a file from opening. The number after startxref is the only route from the end of the file into its structure.
Incremental updates, worked example#
An incremental update appends to the file instead of rewriting it (§7.5.6): new or changed objects, a new cross-reference section listing only those objects, and a new trailer whose /Prev points at the previous section. The original bytes are left exactly as they were. Deleted objects stay in the file too; only their cross-reference entries change, to free.
The minimal-updated.pdf example is the 592-byte file from the anatomy page plus one update that replaces the text. The first 592 bytes are unchanged; this is what follows them:
592 5 0 obj
600 << /Length 48 >>
617 stream
624 BT /F1 24 Tf 72 770 Td (Hello again, PDF.) Tj ET
673 endstream
683 endobj
690 xref
695 0 1
699 0000000000 65535 f
719 5 1
723 0000000592 00000 n
743 trailer
751 << /Size 6 /Root 1 0 R /Prev 409 >>
788 startxref
798 690
802 %%EOFFollow the reader. startxref says 690, so it parses the section there: a subsection for object 0 (free, as required) and a subsection 5 1 saying object 5 now starts at byte 592. The trailer repeats /Size and /Root and adds /Prev 409. Because object 5 is already known, the reader records it and moves on to the section at 409, the original table, taking entries for objects 1 to 4 and ignoring its older entry for object 5. The new content stream at byte 592 wins; the old one at byte 349 is unreachable. A viewer shows "Hello again, PDF." and nothing hints that the file ever said anything else.
/Prev leads to the older one, and entries already seen are not overridden by older sections.This design has consequences people run into constantly:
- "Deleted" content survives. Drawing a black rectangle over text and saving creates an update whose new content stream still references, or is appended after, the original stream. The old bytes remain readable with any tool that ignores the index. Real redaction rewrites the content and then saves a fresh file. The same applies to removed pages, old form values and earlier versions of metadata.
- Files only grow. Each save with incremental updates adds bytes; a document edited fifty times carries fifty trailers. Rewriting the file (a plain
qpdf in.pdf out.pdf) produces a single section containing only objects reachable from the final trailer; qpdf's--preserve-unreferencedkeeps the rest if you want it. - Digital signatures depend on it. A signature covers a byte range of the file; later changes are appended as updates so the signed bytes stay intact, and a reader can show exactly what was signed and what was added afterwards.
- The header version can be overridden. An update may raise the version via
/Versionin the catalog without touching%PDF-1.4at byte 0.
Hybrid-reference files#
PDF 1.5 introduced compressed cross-reference streams (next section), which readers built for earlier versions cannot parse. To stay compatible, a writer can produce a hybrid file: a classic table whose trailer carries /XRefStm, the offset of a cross-reference stream holding the entries for objects stored in object streams. A 1.5-aware reader that fails to find an object in a table section checks the /XRefStm stream before following /Prev; an older reader ignores the key, finds the objects marked free in the classic table, and simply does not see them (§7.5.8.4). Acrobat wrote hybrid files for years, and the /XRefStm key is the reliable sign of one.
Cross-reference streams#
A cross-reference stream stores the same information as a table in binary form inside a stream object with /Type /XRef (§7.5.8). Because it is a stream it can be compressed, and because it is an object it sits in the body like any other; startxref then points at the object, not at an xref keyword, which is the first thing a parser written for 1.4 files trips over. The stream dictionary doubles as the trailer: /Size, /Root, /Info, /ID, /Encrypt and /Prev appear in it directly, so there is no separate trailer keyword.
Three keys describe the layout (Table 17). /W is an array of three field widths in bytes; /Index lists subsection pairs (first object number, count) and defaults to [0 /Size]; /Size is as in a trailer. Each entry is the three fields concatenated, big-endian, with types from Table 18:
| Field 1 (type) | Field 2 | Field 3 | Equivalent in a table |
|---|---|---|---|
| 0 | next free object number | generation to use on reuse | f entry |
| 1 | byte offset of the object | generation number (default 0) | n entry |
| 2 | object number of the containing object stream | index of the object within that stream | no equivalent: the object is compressed |
/W; a width of 0 omits the field and uses its default (type defaults to 1).The xref-stream.pdf example (884 bytes, written by pdf-lib 1.17.1 with object streams enabled) ends with this object:
8 0 obj
<<
/Size 9
/Root 2 0 R
/Info 3 0 R
/Filter /FlateDecode
/Type /XRef
/Length 42
/W [ 1 2 2 ]
/Index [ 0 9 ]
>>
stream
(42 bytes of Flate-compressed data)
endstream
endobj
startxref
679
%%EOFpdf-lib writes /W [1 2 2], two bytes for the third field, so each entry is 5 bytes and nine entries inflate to 45 bytes. Decoding them with Node's zlib.inflateSync and splitting into 5-byte rows gives:
obj 0: 00 0000 ffff type 0 free, next free 0, generation 65535
obj 1: 02 0007 0000 type 2 object 1 is entry 0 of object stream 7
obj 2: 02 0007 0001 type 2 object 2 is entry 1 of object stream 7
obj 3: 02 0007 0002 type 2 object 3 is entry 2 of object stream 7
obj 4: 02 0007 0003 type 2 object 4 is entry 3 of object stream 7
obj 5: 02 0007 0004 type 2 object 5 is entry 4 of object stream 7
obj 6: 01 0010 0000 type 1 object 6 at byte 16 (the content stream)
obj 7: 01 00c7 0000 type 1 object 7 at byte 199 (the object stream)
obj 8: 01 02a7 0000 type 1 object 8 at byte 679 (this stream)qpdf --show-xref reports the same thing in words: objects 1 to 5 "compressed; stream = 7, index = 0" to 4, and objects 6 to 8 "uncompressed" at offsets 16, 199 and 679. Note that the stream contains an entry for itself (object 8), as the specification requires.
Many writers, Acrobat among them, add /DecodeParms << /Predictor 12 /Columns 5 >> to the stream. That means each row was run through the PNG "Up" filter before Flate compression: an extra leading byte per row holds the filter type (2 for Up), and every byte must be added to the byte directly above it from the previous row. Consecutive entries differ by small amounts, so the predicted rows compress much better. A parser must undo the predictor row by row before reading fields; the algorithms are the ones in the PNG specification, with the row width given by /Columns.
Object streams#
Object streams (§7.5.7) are why the catalog, the page tree and the font dictionary of the example are nowhere to be seen in a text editor. An object stream is a stream with /Type /ObjStm, /N (number of objects inside) and /First (byte offset, within the decoded data, of the first object). The decoded data begins with /N pairs of integers, object number and offset relative to /First, followed by the objects themselves written one after another without obj and endobj. Here is object 7 of the example after inflating it:
1 0 2 44 3 78 4 394 5 476 <<
/Type /Pages
/Kids [ 5 0 R ]
/Count 1
>>
<<
/Type /Catalog
/Pages 1 0 R
>>
<<
/Producer <FEFF...>
/CreationDate (D:20261029000000Z)
/Title <FEFF...>
>>
<<
/Type /Font
/Subtype /Type1
/BaseFont /Helvetica
/Encoding /WinAnsiEncoding
>>
<<
/Type /Page
/Parent 1 0 R
/Resources << /Font << /Helvetica-7098480789 4 0 R >> >>
/MediaBox [ 0 0 595.28 841.89 ]
/Contents [ 6 0 R ]
>>The header 1 0 2 44 3 78 4 394 5 476 says object 1 starts 0 bytes after /First, object 2 at 44, object 3 at 78, and so on; the five dictionaries follow in that order. Only non-stream objects can live here, their generation must be 0, and in an encrypted file the whole object stream is encrypted rather than its individual strings. References to these objects look exactly like any other (4 0 R), which is the point: readers resolve them through the type-2 entries of the cross-reference stream without the author of the referencing object caring where they are stored.
Reading a modern file in a text editor#
Every PDF written by a current library or by Acrobat uses cross-reference streams and object streams, so opening one in an editor shows compressed binary where the structure should be. qpdf undoes that in one step:
qpdf --qdf --object-streams=disable input.pdf readable.pdfQDF mode writes every object uncompressed, one dictionary entry per line, expands object streams back into top-level objects, renumbers in reading order, and annotates the result with comments such as %% Original object ID: 5 0 and %% Page 1. The first lines of the example after conversion:
%PDF-1.7
%QDF-1.0
%% Original object ID: 2 0
1 0 obj
<<
/Pages 3 0 R
/Type /Catalog
>>
endobjEdit anything you like, run fix-qdf readable.pdf > fixed.pdf to recompute stream lengths and the cross-reference table, and the file opens again. Converting back to compact form is just qpdf fixed.pdf final.pdf.
Linearized files#
A linearized file is arranged so that a viewer can begin to display it before it has fully downloaded. qpdf, which can write and check the layout, describes its parts as a linearization parameter dictionary and hint streams that contain offset information for the file's objects: with them, a viewer that can request byte ranges knows where the objects for each page lie and asks only for those. Over HTTP that needs a server that answers range requests, which the MIME type page covers; a reader that does not use the hints reads the file as an ordinary PDF.
Linearization is a property of how the bytes are ordered, not of what the document contains, so any tool that rewrites a file decides afresh whether to linearize it. The PDF inspector reports a file as linearized when a /Linearized dictionary appears in its first 2 KB; it does not validate the hint streams, which qpdf can do:
# write a linearized (web-optimized) copy
qpdf --linearize in.pdf out.pdf
# check the linearization parameter dictionary and the hint streams
qpdf --check-linearization file.pdfDamaged tables and how to rebuild them#
Because offsets are absolute, any byte-level edit, a truncated download, or a writer that miscounted produces a file whose table points at the wrong places. Readers treat this as recoverable: on failure to find obj at an offset they scan the whole file for lines matching N G obj and rebuild the table from what they find, taking the last definition of each object number as current. qpdf reports the condition as "xref table damaged" or "file is damaged" during --check and still proceeds; mutool's show -r forces the same repair; pdf.js does it silently in the browser. Repair is a heuristic, though. It cannot know whether a later duplicate of an object was a legitimate update or leftover junk, and it has no way to recover entries for objects inside an object stream whose own entry is gone unless it decodes every object stream it finds.
To rebuild the table, let a tool run that recovery and write a new file. qpdf attempts it whenever it meets a damaged cross-reference table (the --suppress-recovery option turns it off), and every file it writes carries a cross-reference section it generated itself; MuPDF documents mutool clean as a way to repair broken files. Both rely on heuristics that do not work on every file, so check the copy before replacing the original: its page count and text should match what a viewer shows for the damaged file.
# report the damage (qpdf attempts recovery while it checks)
qpdf --check damaged.pdf
# write a copy with a newly generated cross-reference table, with either tool
qpdf damaged.pdf rebuilt.pdf
mutool clean damaged.pdf rebuilt.pdf
# check the copy
qpdf --check rebuilt.pdfThese commands follow the qpdf and MuPDF manuals; they were not run on the machine that built this page.
Commands#
# structural check; reports damaged tables, bad offsets and stream errors
qpdf --check file.pdf
# every entry of the final table, including compressed (object-stream) entries
qpdf --show-xref file.pdf
# the trailer dictionary and the raw cross-reference table
mutool show file.pdf trailer
mutool show file.pdf xref
# summary including version, page count and whether the file was updated incrementally
pdfcpu info file.pdf
# write a single-section file, dropping superseded objects
qpdf file.pdf rewritten.pdfCounting %%EOF markers is a quick, reliable way to tell how many revisions a file carries; the PDF inspector does that in the browser, along with reporting whether the final section is a table or a stream.
Sources
- ISO 32000-1:2008, §7.5.4 Cross-reference table, §7.5.5 File trailer (Table 15) PDF 1.7, distributed free of charge by Adobe
- ISO 32000-1:2008, §7.5.6 Incremental updates, §7.5.7 Object streams (Table 16), §7.5.8 Cross-reference streams (Tables 17, 18, 19)
- ISO 32000-1:2008, Annex H.7 Updating example
- qpdf manual, object and cross-reference streams
- qpdf manual, QDF mode and fix-qdf
- qpdf manual, linearization
- qpdf manual, command-line options (--linearize, --check-linearization, --suppress-recovery)
- MuPDF documentation, mutool clean
- Portable Network Graphics (PNG) specification, filtering (the predictor algorithms PDF borrows)
- RFC 1950 (zlib) and RFC 1951 (DEFLATE), the format behind FlateDecode