PDF objects and syntax
Everything in a PDF file is built from eight kinds of value, combined with two keywords that turn a value into a numbered object. The grammar is small enough to learn in an afternoon and stable enough that a file written in 1993 still parses under the rules below. The anatomy page showed where objects sit in a file; this page is about what they are made of, and ends with the operators that appear inside a page's content stream.
Tokens, delimiters and comments#
A reader splits the file into tokens using three character classes (ISO 32000-1 §7.2.2). White space is any of NUL, tab, line feed, form feed, carriage return and space; runs of it collapse to one separator, and a lone CR, a lone LF or CR LF all count as one end of line. The delimiters are the ten characters ( ) < > [ ] { } / %; each ends whatever token came before it and is never part of a name or number. Everything else is a regular character, including bytes above 127, and a run of regular characters is one token. PDF is case-sensitive: /Type and /type are different names.
A % outside a string or stream starts a comment that runs to the end of the line, and a reader treats the whole comment as a single space (§7.2.3). The header %PDF-1.7 and the end-of-file marker %%EOF are comments syntactically; their meaning comes from the file-structure rules, not from the lexer. Comments have no other semantics and editors are free to drop them.
The eight object types#
| Type | Written as | Example | Notes |
|---|---|---|---|
| Boolean | true or false | /Marked true | §7.3.2 |
| Numeric | integer or real | 42, -3, 595.28, .5 | No exponent notation and no radix prefixes (§7.3.3) |
| String | literal in parentheses or hex in angle brackets | (Hello), <48656C6C6F> | A sequence of bytes; the context decides the text encoding (§7.3.4) |
| Name | slash followed by regular characters | /Type, /F1, /A#20B | Atomic symbol; #xx escapes any byte (§7.3.5) |
| Array | square brackets | [0 0 595.28 841.89] | Elements may be of mixed types and may nest (§7.3.6) |
| Dictionary | double angle brackets | << /Type /Page /Count 1 >> | Keys are names; values are any object (§7.3.7) |
| Stream | dictionary, then stream … endstream | see below | Unlimited binary data; must be an indirect object (§7.3.8) |
| Null | null | /Dest null | Equivalent to an absent entry (§7.3.9) |
Numbers#
Integers are a sign and decimal digits. Reals add a period, which may lead (.5), trail (4.) or sit in the middle; a real does not carry an exponent, so a writer that emits 6.02e23 has produced a syntax error that lenient readers may or may not forgive. There is no distinction between the number 1 and the number 1.0 beyond their spelling. Numbers appear everywhere: as dimensions in points, as object numbers, as operands to drawing operators.
Strings#
A literal string sits between parentheses and may contain any bytes, including balanced parentheses and line breaks. A backslash escapes the sequences in Table 3 of the specification: \n, \r, \t, \b, \f, \(, \), \\, and \ddd for an octal byte value of one to three digits. A backslash at the end of a line joins the string across the break, and a bare line break inside a string is read as a single line feed byte whatever the file's line ending. A hexadecimal string sits between angle brackets, two hex digits per byte, white space ignored, and a missing final digit is read as 0.
Which encoding the bytes use is decided by where the string appears, not by the syntax. Text strings such as a document title use PDFDocEncoding, or UTF-16BE when they begin with the byte order mark FEFF; that is why a title written by a modern library looks like <FEFF007800720065...> when you open the file in an editor. Strings inside a content stream are not text in this sense at all: they are sequences of character codes that a font maps to glyphs, which is the subject of the fonts page.
Names#
A name is an atomic symbol: /Type, /MediaBox, /F1. The slash is a prefix, not part of the name. Any byte other than NUL can be included by writing # followed by two hex digits, so /lime#20Green is the name lime Green and /paired#28#29parentheses contains a pair of parentheses. Names are compared byte by byte and have no internal structure, which is why the specification treats /A#20B as three characters, not six. The names that matter are the dictionary keys defined by the standard (/Type, /Pages, /Filter, and several hundred more) and the resource names an author chooses, such as /F1 for a font.
Arrays and dictionaries#
An array is an ordered list of any objects, including other arrays and dictionaries, and including references to indirect objects. A rectangle is an array of four numbers; a page tree's /Kids is an array of references.
A dictionary maps names to objects. Keys must be unique within a dictionary, and the order of entries carries no meaning. An entry whose value is null is treated as if it were absent (§7.3.7), which is the easiest way to think about optional keys: a reader asking for /CropBox and finding nothing falls back to the default exactly as if it had found null. Most dictionaries that describe a kind of thing carry a /Type entry naming that kind (/Page, /Font, /XObject), and some carry a /Subtype as well.
Streams#
A stream is the only object type that can hold an unlimited amount of data, so page content, images, fonts and embedded files are all streams. The syntax is a dictionary, the keyword stream, an end-of-line marker (CR LF or LF, never a lone CR), the data, and the keyword endstream. Every stream dictionary must have /Length, the number of bytes between the end of line after stream and the byte before endstream; when the data is filtered, the count is of the encoded bytes as they sit in the file (§7.3.8.2). Streams are always indirect objects, so a stream cannot be written inline as a dictionary value.
7 0 obj
<< /Length 1234 /Filter [/ASCII85Decode /FlateDecode] /DecodeParms [null << /Predictor 12 /Columns 4 >>] >>
stream
GhVOz9lm... (1234 bytes of encoded data)
endstream
endobj/Filter names the decoding filters a reader applies, in order: the example above is first ASCII85-decoded, then inflated. /DecodeParms supplies per-filter parameters in a matching array, with null for filters that take none. The compression page covers each filter.
Null#
null is a value that means "nothing here". Besides standing in for absent dictionary entries, it is what a reader gets when it resolves a reference to an object that does not exist, which is explicitly not an error (§7.3.10).
Direct and indirect objects#
Any object can be given a number and written at the top level of the file as an indirect object:
12 0 obj
(Brillig)
endobj
% elsewhere in the file:
<< /Title 12 0 R >>The two integers are the object number and the generation number, and together they identify the object. 12 0 R is an indirect reference: the three tokens are read as one value that means "whatever object 12, generation 0, contains". Numbers need not be sequential or contiguous, and the same object may be referenced any number of times, which is how one font dictionary serves every page of a document.
Generation numbers start at 0 and only change if an object number is freed and later reused, a mechanism described on the xref page. Files written since 2000 almost never contain a generation other than 0. From PDF 1.5, non-stream objects may also live inside object streams; they keep their numbers and are referenced the same way, but their definition omits obj and endobj and their generation is always 0.
Where to use a reference and where to write a value inline is mostly the writer's choice. The standard forces a reference in a few places (the /Parent of a page, and every stream) and forbids it in a few others (/Size in the trailer, the /ID array of an encrypted file). It explicitly allows a stream's /Length to be a reference, so that a writer streaming data of unknown size can emit the count afterwards as a separate object. Writers typically make anything shared or large indirect and keep small values inline.
Operators in a content stream#
A page's /Contents stream holds a program in a tiny postfix language: operands come first, then the operator (§7.8.2). Operands are ordinary PDF objects (numbers, names, strings, arrays, inline dictionaries); operators are bare keywords. There are no variables, no loops and no references to other objects except by name through the page's /Resources dictionary, which is what /F1 means in /F1 24 Tf: look up the font registered under /F1 in the resources.
The specification groups the operators into categories (Table 51). The ones you will meet in almost every file:
| Category | Operators | Effect | Clause |
|---|---|---|---|
| Graphics state | q Q cm w J j d gs | Save and restore state, concatenate a transformation matrix, set line width, caps, joins, dashes, or apply a named parameter dictionary | §8.4.4 |
| Path construction | m l c v y h re | Move to, line to, Bézier curves, close subpath, rectangle | §8.5.2 |
| Path painting | S s f f* B B* b b* n | Stroke, fill (nonzero or even-odd), fill and stroke, or end the path without painting | §8.5.3 |
| Clipping | W W* | Intersect the clip with the current path (takes effect after the painting operator) | §8.5.4 |
| Colour | g G rg RG k K cs CS sc scn SC SCN | Set fill (lowercase) or stroke (uppercase) colour in gray, RGB, CMYK or a named colour space | §8.6.8 |
| Text objects and state | BT ET Tf Tc Tw Tz TL Tr Ts | Begin and end a text object; set font and size, character and word spacing, scaling, leading, render mode, rise | §9.4.1, §9.3.1 |
| Text positioning | Td TD Tm T* | Move the text position, set the text matrix, start a new line | §9.4.2 |
| Text showing | Tj TJ ' " | Show a string, or an array of strings with positioning adjustments | §9.4.3 |
| External objects | Do | Paint an image or form XObject named in the resources | §8.8 |
A short stream that draws a filled rectangle with a border and a line of text reads like this:
q % save graphics state
0.9 0.9 0.9 rg % fill colour: light gray (RGB)
0 0 1 RG % stroke colour: blue
1.5 w % line width 1.5 pt
72 700 200 60 re % rectangle: x y width height
B % fill and stroke it
Q % restore state (colours and width revert)
BT % begin text
/F1 18 Tf % font F1 from /Resources at 18 pt
84 722 Td % text position
(Objects and syntax) Tj % show the string
ETThree habits of the language are worth internalising. Coordinates are in user space, points by default, with the origin at the bottom left of the page, so 72 700 is one inch from the left and about 1.4 inches below the top of an A4 page. Nothing is drawn until a painting operator runs; re only builds a path. And the graphics state is a stack: q pushes a copy, Q pops it, which is how generators isolate the colour and transformation changes of one element from the next. The cm operator multiplies a matrix into the state, which is how images are placed (an image XObject is drawn into the unit square, so 200 0 0 150 72 500 cm /Im1 Do paints it 200 pt wide and 150 pt tall at (72, 500)).
Text uses its own matrix inside BT … ET, and the string operand of Tj is not Unicode: each byte (or byte pair for composite fonts) is a code that the font's encoding maps to a glyph. That indirection is why copying text from some PDFs yields nonsense, and the fonts page explains the ToUnicode map that fixes it.
Reading objects by hand#
Content streams in real files are compressed, dictionaries are written on one line, and since PDF 1.5 most objects are tucked inside object streams. Two commands turn any file into the readable form used on this page:
# rewrite with uncompressed streams, expanded object streams, one entry per line
qpdf --qdf --object-streams=disable input.pdf readable.pdf
# print the trailer, then object 3, then page 1 by path
mutool show input.pdf trailer
mutool show input.pdf 3
mutool show input.pdf pages/1The QDF output adds comments such as %% Original object ID: 5 0 and renumbers objects; if you edit it and change any lengths, fix-qdf repairs the stream lengths and the cross-reference table so the file opens again. That round trip, edit a dictionary, run fix-qdf, open the result, is the fastest way to confirm what a key actually does.
Sources
- ISO 32000-1:2008, §7.2 Lexical conventions (character set, delimiters, comments) PDF 1.7, distributed free of charge by Adobe
- ISO 32000-1:2008, §7.3 Objects (7.3.2 booleans to 7.3.10 indirect objects), Tables 3, 4 and 5
- ISO 32000-1:2008, §7.8 Content streams and resources; §8.2 Graphics objects and Table 51 operator categories
- ISO 32000-1:2008, §8.4.4, §8.5.2, §8.5.3, §8.6.8, §9.4.2, §9.4.3 (operator definitions)
- qpdf manual, QDF mode
- MuPDF, mutool show