← PDF
PDF·Format guide
All tools

How a PDF file is built

PDF (Portable Document Format, ISO 32000) describes pages as programs of drawing operators, together with the fonts, images and other resources they use. Around them, a PDF file is a small database of numbered objects with an index (the cross-reference) that gives each object's byte offset, so a reader can jump to any object without reading the whole file. This page describes the layout as the PDF tool reads it, what in a PDF matters for security, and the PdfDocument library.

Contents

  1. File layout
  2. Objects and their syntax
  3. Streams and filters
  4. The cross-reference: tables and streams
  5. Object streams
  6. Incremental updates and linearization
  7. The document structure
  8. Encryption
  9. What to look for
  10. What the tool shows, and its limits
  11. The PdfDocument library

1File layout

A PDF is mostly ASCII text with binary data inside streams. Read from the start, it is:

PartLooks likeMeaning
header%PDF-1.7The version. It must be in the first 1024 bytes (readers accept junk before it). The catalog's /Version can raise it later, which an incremental update cannot do for the header.
binary comment%âãÏÓA comment line with at least four bytes ≥ 128, so that transfer programs treat the file as binary and don't convert line endings.
body1 0 obj … endobjThe objects, in any order.
cross-referencexref
0 6
0000000000 65535 f
0000000015 00000 n
Where each object starts (section 4).
trailertrailer << /Size 6 /Root 1 0 R >>The number of entries, the catalog (/Root), the Info dictionary, the /ID pair, /Encrypt, and /Prev for an update.
endstartxref
1234
%%EOF
The offset of the cross-reference. A reader starts at the end of the file: it finds startxref, jumps to the cross-reference, reads the trailer, then the catalog.

Bytes after the last %%EOF are ignored by readers, which makes them a place to hide data. A file whose cross-reference is missing or wrong is usually still opened: readers scan the whole file for n g obj and rebuild the index, each in its own way.

2Objects and their syntax

White space is NUL, tab, LF, FF, CR and space; the delimiters are ( ) < > [ ] { } / %; % starts a comment that runs to the end of the line. There are eight kinds of values:

KindExamplesNotes
boolean, nulltrue false null
number12 -3 4.5 .5 +7Integers and reals; no exponents.
literal string(Hello \(world\)\n)Balanced parentheses nest without escaping. Escapes: \n \r \t \b \f \( \) \\, \ddd in octal; a backslash before an end of line continues the line; an unescaped end of line becomes LF.
hex string<48656C6C6F>White space is ignored; an odd last digit is followed by 0. Text strings are PDFDocEncoding (close to Latin-1), or UTF-16BE starting with FE FF (or UTF-8 with EF BB BF, PDF 2.0).
name/Type /A#20BA symbol. #xx is a byte in hex, so /JavaScript can be written /J#61vaScript, a trick to escape naive scanners.
array[0 0 595 842]Any values, mixed.
dictionary<< /Type /Page /Rotate 90 >>Name keys, any values. A key whose value is null is the same as a missing key.
stream<< /Length 44 >> stream … endstreamA dictionary followed by bytes (section 3). Always an indirect object.

An indirect object is a value with a number and a generation: 12 0 obj << … >> endobj. Elsewhere, 12 0 R is a reference to it. A reference to an object that doesn't exist is null. The generation starts at 0 and grows when an object number is freed and used again.

3Streams and filters

After the keyword stream and an end of line (LF or CR LF) come exactly /Length bytes, then endstream. /Length may be a reference, often to an object written after the stream (the producer only knows the length once it has written the data). When /Length is wrong, readers search for endstream. /Filter (a name or an array) says how the bytes are encoded, applied in order to decode; /DecodeParms gives each filter its parameters.

FilterEncodingThe tool
FlateDecode (Fl)zlib/DEFLATE, the usual compression; with /Predictor 2 (TIFF differences) or 10–15 (PNG row filters, one filter byte per row of /Columns × /Colors × /BitsPerComponent)decodes
LZWDecode (LZW)LZW with 9 to 12-bit codes, /EarlyChange; predictors as for Flatedecodes
ASCIIHexDecode (AHx)two hex digits per byte, ending with >decodes
ASCII85Decode (A85)base-85: 5 characters for 4 bytes, z for 4 zero bytes, ending with ~>decodes
RunLengthDecode (RL)a length byte: copy the next 1–128 bytes, or repeat the next byte 2–128 times; 128 endsdecodes
DCTDecode · JPXDecodea JPEG or JPEG 2000 image: the stream is the image fileleft as is (download it)
JBIG2Decode · CCITTFaxDecodebi-level image codecsleft as is
Crypta stream's own crypt filter (section 8); /Identity does nothingapplied with the key

A few bytes can inflate to gigabytes (a “decompression bomb”): the library stops a filter at 64 MB.

4The cross-reference: tables and streams

A classic table is the keyword xref, then subsections: a line “first count”, then count entries of exactly 20 bytes: a 10-digit offset, a 5-digit generation, n (in use) or f (free; the offset is then the next free object number), and a 2-byte end of line. Object 0 is always free with generation 65535. The trailer dictionary follows.

Since PDF 1.5 the cross-reference can be a stream (/Type /XRef), usually Flate-compressed with a PNG predictor. Its dictionary is the trailer too (/Size /Root /Info /ID /Encrypt /Prev). /W [1 2 1] gives the byte widths of three fields per entry; /Index [first count …] the ranges of numbers (default [0 /Size]). The first field is the type (1 when its width is 0):

TypeField 2Field 3
0next free objectgeneration for the next use
1byte offset of an object in the filegeneration
2the object stream that holds itits index in that stream

A hybrid file has both: a classic table that older readers use, whose trailer has /XRefStm, the offset of a cross-reference stream that lists the compressed objects (marked free in the table). Newer readers merge the two.

5Object streams

An object stream (/Type /ObjStm, PDF 1.5) packs many small objects together so they compress well. Its decoded data starts with /N pairs “object-number offset”, then the objects themselves from byte /First, written without obj / endobj. Streams, the encryption dictionary and objects with a generation other than 0 cannot be inside one. Because the catalog, pages and annotations are often compressed, a text search of the raw file finds nothing: JavaScript can hide inside an object stream. /Extends links object streams into a collection.

6Incremental updates and linearization

An edit, a form filled in, an added signature, or an annotation is saved by appending: the new and changed objects, a cross-reference that lists only them (and the freed ones), and a trailer whose /Prev points to the previous cross-reference, then another startxref and %%EOF. The reader follows the /Prev chain back; the newest entry for each number wins. So every earlier revision is still in the file: deleted pages, old text, redacted content and earlier metadata can be recovered by reading the older objects. The tool lists each revision with its byte range and the objects it changed, and keeps the older versions of objects in the Objects table.

A signature covers /ByteRange: the file from 0 up to its own /Contents, and from after it to the end of its revision. Updates after signing are allowed (later signatures, form filling) but they can also change what is shown (“shadow attacks”); the tool says when a signature doesn't cover the whole file.

A linearized file (“fast web view”) starts with a linearization dictionary (/Linearized 1 /L file length, /O first page object, /E end of the first page, /N pages, /T the main cross-reference, /H hint stream) and a first-page cross-reference section near the start, so a browser can show the first page before the rest arrives. Its /Prev points to the main section at the end. Once the file is updated, /L no longer matches and readers ignore the linearization.

7The document structure

ObjectHolds
catalog (/Root)/Pages (the page tree), /Outlines, /Names (name trees: /Dests, /JavaScript, /EmbeddedFiles), /AcroForm, /Metadata (XMP), /OpenAction, /AA, /PageLabels, /Version.
page tree/Pages nodes with /Kids and /Count, down to /Page leaves. /MediaBox (the page size in points, 1/72 inch), /CropBox, /Rotate and /Resources are inherited from the nearest ancestor that has them.
page/Contents (one content stream or an array: the drawing operators, such as BT /F1 12 Tf (text) Tj ET), /Resources (/Font, /XObject, /ExtGState, /ColorSpace… by name), /Annots, /AA.
font/Subtype Type1, TrueType, Type0 (with /DescendantFonts), Type3; /BaseFont (a ABCDEF+ prefix marks a subset); /FontDescriptor with the embedded program in /FontFile (Type 1), /FontFile2 (TrueType) or /FontFile3 (CFF, OpenType); /ToUnicode maps glyphs back to text.
image XObjectA stream with /Subtype /Image, /Width, /Height, /BitsPerComponent, /ColorSpace, /SMask (transparency). Form XObjects (/Subtype /Form) are reusable bits of content.
annotation/Subtype Link (with /A an action or /Dest), Widget (form fields), FileAttachment, Text, RichMedia…, and its /Rect.
Info, XMPThe trailer's /Info: /Title /Author /Subject /Keywords /Creator /Producer /CreationDate /ModDate (dates are D:YYYYMMDDHHmmSS+HH'mm'). The catalog's /Metadata stream is XMP (XML), with the same and more, such as the editing history and document IDs.

8Encryption

The trailer's /Encrypt dictionary encrypts every string and stream (not names, numbers, the cross-reference stream, or the /Encrypt dictionary itself). With the standard security handler (/Filter /Standard), a key is derived from the user password; the owner password only unlocks the permissions.

/V · /RAlgorithmKey
1 · 2RC4, 40-bitMD5 of the padded password, /O, /P and the first /ID
2 · 3RC4, 40 to 128-bitthe same, with 50 more MD5 rounds
4 · 4crypt filters (/CF, /StmF, /StrF): RC4 (/V2) or AES-128 (/AESV2)as R3; each object's key is the MD5 of the file key, its number and generation (and “sAlT” for AES)
5 · 5, 6AES-256 (/AESV3), PDF 2.0SHA-256 (R5) or rounds of SHA-256/384/512 and AES (R6) of the password and a salt; the file key itself is in /UE and /OE, encrypted; /Perms protects /P

/P is a 32-bit signed number whose bits allow (1) or deny (0) actions: 3 print, 4 modify, 5 copy text and graphics, 6 annotate and fill forms, 9 fill forms, 10 extract for accessibility, 11 assemble pages, 12 print at full quality. Most encrypted PDFs have an empty user password: they open without asking, anyone can compute the key, and the permissions are only a request to well-behaved viewers. The tool tries the empty password; when it works, strings and streams are decrypted for display. /Adobe.PubSec encrypts the key for certificates instead, and can't be opened without a private key.

9What to look for

10What the tool shows, and its limits

The overview (version, pages, encryption, linearization, updates, JavaScript and other findings, the Info and XMP facts, problems, and a bar of how the file's bytes are used); every object, current and older, with its dictionary as indented PDF syntax whose references open the object they point to (with back and forward), and its stream decoded as text or hex, to download; the pages with their sizes, contents, fonts and annotations; the cross-reference sections, trailers and revisions, the linearization and the object streams; the security findings, the encryption and its permissions, the signatures, the links and unreferenced objects; fonts, images, metadata and the outline.

It doesn't draw pages, images or fonts, and doesn't interpret content streams. It decrypts only with the empty user password (RC4 and AES-128 with revisions 2 to 4, AES-256 with 5 and 6), not with a password you type or with certificates. It doesn't verify signatures (the CMS in /Contents), hint streams, or the meaning of form fields, and it doesn't run JavaScript. For the bytes themselves, objects and decoded streams open in the Hex tool.

11The PdfDocument library

lib/pdf.js is a JavaScript module with no user interface. It imports lib/pdf-objects.js (the values and the parser), lib/pdf-filters.js (the filters, with lib/compression/inflate.js) and lib/pdf-encryption.js (with lib/crypto/ MD5, SHA-256, AES and CBC), and re-exports their classes. It works synchronously, in a page, a worker or jsc.

import { PdfDocument, PdfName, PdfString, PdfReference, PdfDictionary, PdfStream, PdfValue } from "../lib/pdf.js";
MemberWhat it is
PdfDocument.open(bytes, options)Reads a PDF from a Uint8Array; throws when there is no %PDF- header in the first 1024 bytes. options.decodeLimit: the most one stream may decode to (64 MB).
PdfDocument.isPdf(bytes)Whether the header is there.
PdfDocument.parseDate(text)A PDF date (D:20261130120000+01'00') as ISO 8601, or null.
pdf.version · catalogVersion · headerOffset · binaryComment · sizeThe header's version, the catalog's /Version, where the header is, the binary comment { offset, bytes, ok }, the file length.
pdf.object(number, generation)The current object (a PdfObject), read when first asked for, or null. The generation is optional.
pdf.resolve(value) · pdf.get(dictionary, key)A value with references followed; a dictionary entry, resolved.
pdf.stream(objectOrStream, options){ bytes, raw, applied, stoppedAt, error, warning, encrypted, decrypted }: the data decrypted and decoded; stoppedAt is the first filter left applied (an image codec); options.decode: false only decrypts.
pdf.scriptText(value)A /JS value (a string or a stream, through a reference) as text.
pdf.entries · pdf.instances · pdf.load(instance)The current cross-reference [{ number, generation, kind ("used", "compressed", "free"), offset, streamNumber, streamIndex, revision }]; every object in the file, current, superseded, deleted or in no cross-reference ({ key, number, generation, status, revision, offset, streamNumber, streamIndex, role, referencedBy }); the object of an instance.
pdf.xrefSections · pdf.revisions · pdf.startxref · pdf.eofOffsetsThe sections in the /Prev chain, newest first ({ offset, kind, subsections, entryCount, trailer, streamNumber, hybridOffset, prevOffset, linearizedFirstPage, problems }); the revisions, oldest first ({ index, sections, trailer, entries, start, end, startxref, eofOffset, objects }).
pdf.recovered · pdf.trailing · pdf.layout · pdf.problemsWhether the objects were found by scanning; bytes after the last %%EOF; the byte map ([{ offset, length, type, label, number, revision }]); what is wrong.
pdf.trailer · catalog · info · metadataThe trailer (completed by older ones), the catalog, [{ key, value, date }] from Info, { number, xml, fields } from XMP.
pdf.pages · fonts · images · annotations · links · outlineThe pages with their inherited boxes, rotation, contents, fonts, XObjects and annotations; the fonts and images with the pages that use them; annotations with their actions and URIs; the bookmarks as a tree.
pdf.objectStreams · linearization · acroForm · signaturesWhat each object stream holds; the linearization parameters; the form fields and XFA; the signatures with their byte ranges.
pdf.encryptionA PdfEncryption: filter, version, revision, keyLength, method, cryptFilters, permissions { value, flags }, userPasswordEmpty, canDecrypt, note, decrypt(bytes, number, generation, kind).
pdf.findings · pdf.unreferencedWhat matters for security: [{ severity ("high", "medium", "info"), category, title, detail, object, where }]; the objects nothing reaches from the trailer.
PdfObjectnumber, generation, value, offset, end, streamNumber, problems, error, and dictionary, stream, type, subtype.
PdfName · PdfString · PdfReference · PdfDictionary · PdfStreamThe values: name.name; string.bytes, hex, text; reference.number, generation; dictionary.get(key), has, keys(), entries(), size, type, subtype; stream.dictionary, dataOffset, length, declaredLength, filters. Numbers, booleans, null and arrays are plain JavaScript values.
PdfValue.serialize(value) · kind(value) · isName(value, name)A value written back as indented PDF syntax; its kind; a name test.
new PdfParser(bytes, position)The lexer and parser: value(), token(), indirectObject(), skipSpace(), position.
PdfFilters.decode(bytes, filters, parameters, options)The filters on their own: { bytes, applied, stoppedAt, error }.
const pdf = PdfDocument.open(new Uint8Array(await file.arrayBuffer()));
console.log(pdf.version, pdf.pages.length + " pages", pdf.revisions.length - 1 + " updates");
for (const finding of pdf.findings) {
	console.log(finding.severity, finding.title, finding.detail);
}
for (const number of pdf.pages[0].contents) {
	const content = pdf.stream(pdf.object(number));
	console.log(new TextDecoder().decode(content.bytes));
}