How PDF files work
A PDF is not a page-description program like PostScript and not a markup document like HTML. It is a small object database written out as text, with an index at the end that tells a reader where every object starts. Pages, fonts, images and metadata are all objects in that database; a page is simply an object that points at the other objects it needs. Once you can read the index and follow the pointers, the rest of the format is detail.
This page walks through a complete, valid PDF of 592 bytes. You can download it, open it in any viewer, and follow every offset below in a hex editor. It was generated by a script and checked with qpdf and pdf.js before publication.
The four parts of a file#
Every PDF file has the same large-scale layout: a header, a body of objects, a cross-reference table, and a trailer. The order is fixed, and the reader starts from the end.
startxref, jumps to the cross-reference table, then follows /Root into the body.The reason the index sits at the end rather than the start is historical and practical. A writer can stream objects out as it produces them and only afterwards knows where each one landed, so it writes the offsets last. The same property makes incremental updates possible: new objects and a new index can be appended without touching anything already written. That is covered on the xref and incremental updates page.
The whole file#
Here is the complete document. The left column gives the byte offset at which each line starts, which is what the cross-reference table will refer to. Lines end with a single line feed (byte 0x0A) in this file; carriage return and line feed is equally valid.
0 %PDF-1.7
9 1 0 obj
17 << /Type /Catalog /Pages 2 0 R >>
51 endobj
58 2 0 obj
66 << /Type /Pages /Kids [3 0 R] /Count 1 >>
108 endobj
115 3 0 obj
123 << /Type /Page /Parent 2 0 R /MediaBox [0 0 595.28 841.89] /Resources << /Font << /F1 4 0 R >> >> /Contents 5 0 R >>
240 endobj
247 4 0 obj
255 << /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>
310 endobj
317 5 0 obj
325 << /Length 42 >>
342 stream
349 BT /F1 24 Tf 72 770 Td (Hello, PDF.) Tj ET
392 endstream
402 endobj
409 xref
414 0 6
418 0000000000 65535 f
438 0000000009 00000 n
458 0000000058 00000 n
478 0000000115 00000 n
498 0000000247 00000 n
518 0000000317 00000 n
538 trailer
546 << /Size 6 /Root 1 0 R >>
572 startxref
582 409
586 %%EOFFive objects, one page, one line of text. Everything a reader needs is here, and nothing else.
Header#
The first line, %PDF-1.7, names the version of the syntax the file claims to use. The % makes it a comment, so a PostScript-aware tool ignores it. Readers treat the number as a hint rather than a contract: a file that says 1.4 but uses 1.5 features will usually still open, and the document catalog can override the header with a /Version entry. The versions reference lists what each number added.
Files that contain binary data conventionally add a second comment line with at least four bytes above 127, such as %âãÏÓ, so that transfer tools treat the file as binary. The example file omits it because it is pure ASCII.
The specification requires the header on the first line, and that is what you should write. Readers are more tolerant: Acrobat, for example, accepts a header anywhere in the first 1024 bytes, which is why some PDFs have junk before %PDF. The file signatures reference covers what to check when identifying a file.
Body: five objects#
Each object in the body has the form N G obj … endobj, where N is the object number and G is the generation number. The generation is almost always 0; it only increments when an object number is freed and reused, which modern writers never do. Objects can appear in any order and need not be contiguous. The numbers are what matter, because every reference in the file uses them.
A reference looks like 2 0 R: object 2, generation 0. It is a pointer, and the reader resolves it through the cross-reference table. The content of the objects themselves follows the object syntax: dictionaries between << and >>, arrays in brackets, names starting with /, strings in parentheses, and streams for bulk data.
Object 1, the document catalog, is the root of the graph. Its only required entry is /Pages, which points at the page tree. Real catalogs also carry the outline (bookmarks), the interactive form, metadata, viewer preferences and page labels, but none of those are required.
Object 2, the page tree node, lists its children in /Kids and the total number of leaf pages beneath it in /Count. Large documents nest tree nodes so that a reader can reach page 4,000 without walking 3,999 pages; the specification allows any depth. A one-page file has a single node with one kid.
Object 3, the page, points back to its parent and declares three things: the size of the page, the resources its content will use, and the content itself. /MediaBox [0 0 595.28 841.89] is A4 in points, 1/72 of an inch each, so 210 mm comes out at 595.28 pt. The lower-left corner is the origin and y increases upwards, which is why the text below is placed at y = 770 to sit near the top. The page-boxes page explains MediaBox and its four siblings. /Resources maps the local name /F1 to the font object, and /Contents names the stream that draws the page.
Object 4, the font, is one of the fourteen standard Type 1 fonts that PDF 1.7 readers must supply themselves, which is why no font program is embedded here. ISO 32000-2 (PDF 2.0) removed that exemption, so a 2.0-conforming file would embed Helvetica or a metric-compatible substitute. For anything beyond the fourteen, and for any text you want to look identical everywhere, you embed, and the fonts page explains how that works.
Object 5, the content stream, is where drawing happens. A stream is a dictionary followed by stream, raw bytes, and endstream; the dictionary's /Length says how many bytes sit between the two keywords (42 here, excluding the line breaks around them). The bytes are a sequence of operators in postfix notation:
BT % begin a text object
/F1 24 Tf % select font F1 at 24 pt
72 770 Td % move the text position to x=72, y=770
(Hello, PDF.) Tj % show the string
ET % end the text objectReal content streams are almost always compressed with the Flate filter, so you would see /Filter /FlateDecode in the dictionary and binary bytes in place of the operators. The compression page covers filters; the operators themselves are introduced on the objects and syntax page.
Cross-reference table#
The table begins with the keyword xref and one or more subsections. 0 6 means "entries for six objects starting at object 0". Each entry is exactly 20 bytes: a ten-digit byte offset, a space, a five-digit generation number, a space, n for an object that is in use or f for a free entry, and a two-character end-of-line (here a space followed by a line feed). Fixed width is the point: a reader can seek directly to the entry for object N without parsing the ones before it.
xref
0 6
0000000000 65535 f % object 0 is always free, head of the free list
0000000009 00000 n % object 1 starts at byte 9
0000000058 00000 n % object 2 starts at byte 58
0000000115 00000 n % object 3 starts at byte 115
0000000247 00000 n % object 4 starts at byte 247
0000000317 00000 n % object 5 starts at byte 317Compare the offsets with the left column of the full listing: 1 0 obj really does begin at byte 9 and 5 0 obj at byte 317. If a single byte were inserted anywhere in the body, every offset after it would be wrong and the file would be damaged, which is why you cannot edit a PDF in a text editor and expect it to open. Readers recover from this by scanning the file for obj keywords and rebuilding the table, and qpdf reports it as "xref table damaged" when it does.
Since PDF 1.5 the table can instead be stored as a compressed binary stream, the cross-reference stream, and most of the objects can be packed into object streams. Files written by modern libraries look nothing like the listing above when opened in a text editor, but the model is the same: an index of offsets, plus a trailer pointing to it. Both forms are worked through on the xref page.
Trailer#
The trailer dictionary has two required keys: /Size, one greater than the highest object number in the file, and /Root, the reference to the catalog. Encrypted files add /Encrypt; files with metadata usually add /Info; incrementally updated files add /Prev. After the dictionary comes startxref followed by the byte offset of the cross-reference table, 409 here, and then the end-of-file marker %%EOF.
A reader opens a file by reading backwards from the end: find %%EOF, read the number above it, seek to that offset, confirm the xref keyword, parse the table, parse the trailer, resolve /Root, and only then start following references into the body. Nothing in the body is read until something points to it. That is also why a PDF can contain objects that nothing references at all: they are simply never visited.
What a reader does, in order#
- Read the last 1024 bytes and locate
startxrefand%%EOF. - Seek to the offset after
startxrefand parse the cross-reference section and its trailer. If the trailer has/Prev, repeat for the earlier section, keeping only entries not already seen. - If
/Encryptis present, set up the security handler before decoding any string or stream. - Resolve
/Rootto the catalog, then/Pagesto the page tree, and walk the tree to find page 1 (or the page requested). - For that page, collect inherited attributes (
/MediaBox,/Resources,/Rotateand/CropBoxcan live on ancestor nodes), decode the content stream through its filters, and execute the operators against the page's coordinate system. - Load fonts, images and other resources lazily as the operators name them.
Everything a viewer, a printer driver or a text extractor does is some refinement of those six steps.
Checking this yourself#
The listing above is the actual file, but the habit worth building is inspecting files you did not write. These free tools all run from the command line.
# qpdf: structural check, then every cross-reference entry with its offset
qpdf --check minimal.pdf
qpdf --show-xref minimal.pdf
# mutool (MuPDF): print the trailer and any object by number
mutool show minimal.pdf trailer
mutool show minimal.pdf 3
# pdfcpu: file summary
pdfcpu info minimal.pdf
# qpdf: rewrite a modern compressed file into readable, uncompressed syntax
qpdf --qdf --object-streams=disable input.pdf readable.pdfThe last command is the quickest way to learn the format from real files: --qdf expands object streams, decompresses content streams and renumbers objects so the output can be read, and even edited and fixed up with fix-qdf, in a text editor.
In Python, pypdf exposes the same structure as objects:
from pypdf import PdfReader
reader = PdfReader("minimal.pdf")
print(reader.pdf_header) # %PDF-1.7
print(reader.trailer["/Root"]) # the catalog dictionary
page = reader.pages[0]
print(page.mediabox) # RectangleObject([0, 0, 595.28, 841.89])
print(page.extract_text()) # Hello, PDF.The PDF inspector on this site does the same for any file in the browser, without uploading it: version, cross-reference type, page sizes and boxes, metadata, fonts and encryption.
One file, two revisions#
To see why the trailer and offsets matter, download the updated version of the same file. It is 807 bytes: the original 592 bytes untouched, followed by a new object 5 with different text, a new cross-reference section listing only that object, and a new trailer whose /Prev 409 points at the old table. A viewer shows "Hello again, PDF."; the original "Hello, PDF." is still in the file, at byte 349, for anyone who looks. The xref and incremental updates page takes that file apart.
Sources
- ISO 32000-1:2008, §7.5 File structure (header, body, cross-reference table, trailer, incremental updates) PDF 1.7, distributed free of charge by Adobe
- ISO 32000-1:2008, §7.7 Document structure (document catalog, page tree, page objects)
- ISO 32000-1:2008, §9.6.2.2 Standard Type 1 fonts
- PDF Association, "PDF 2.0 (ISO 32000-2)" overview paywalled standard; only the public overview was consulted
- qpdf manual