PDF compression
Almost every byte in a PDF lives inside a stream: page content, images, embedded fonts, and since PDF 1.5 the object index itself. Compression in PDF is therefore a per-stream matter. Each stream dictionary names the filters that were applied to its bytes, and a reader runs the matching decoders before it can use the data. There is no whole-file compression, which is why a 300-page text document can be smaller than a one-page scan, and why running a "compress PDF" tool over a file can change nothing at all.
This page explains the filters, shows a real file under qpdf, and separates lossless clean-up from the lossy steps that online tools apply without saying so.
Where the bytes go#
A PDF is made of a handful of stream types, and they compress very differently:
- Content streams hold the drawing operators for each page. They are text, highly repetitive, and shrink to a quarter or less with Flate.
- Image XObjects hold sampled pixels. A photograph is usually stored as the original JPEG bytes (DCTDecode), which Flate cannot shrink further. Line art and screenshots do well with Flate, especially with a predictor.
- Font programs are embedded TrueType, CFF or Type 1 files, usually Flate-compressed and, if the producer did its job, subset to the glyphs used. An unsubset CJK font can be several megabytes on its own.
- Structure (dictionaries, arrays, the cross-reference table) is small, and since PDF 1.5 can be packed into object streams and compressed too.
- Attachments, ICC profiles, XMP metadata, thumbnails sit alongside and are easy to forget.
Which of these dominates decides what any compression step can achieve. For a scanned contract, nothing but the images matters. For a generated invoice, the fonts matter more than everything else combined.
The standard filters#
Table 6 of ISO 32000-1 lists ten filters. Two of them (ASCIIHex, ASCII85) expand binary into printable text and are now rare; the rest compress. The version column is what Table 6 states; filters without a note predate PDF 1.2.
| Filter | Kind | Lossless | Typical use | Version |
|---|---|---|---|---|
ASCIIHexDecode | Encoding to text | yes | Debugging, 7-bit transport; doubles the size | |
ASCII85Decode | Encoding to text | yes | Same, with 25% overhead instead of 100% | |
LZWDecode | General compression | yes | Legacy files; superseded by Flate | |
FlateDecode | General compression (zlib/deflate) | yes | Content streams, fonts, object streams, lossless images | PDF 1.2 |
RunLengthDecode | Byte run-length | yes | Simple bilevel data; rarely chosen today | |
CCITTFaxDecode | Bilevel image (Group 3/4 fax) | yes | Scanned black-and-white pages | |
JBIG2Decode | Bilevel image | yes in generic mode; lossy modes exist | Scanned text pages; far smaller than CCITT | PDF 1.4 |
DCTDecode | JPEG (baseline and progressive) | no | Photographs; the JPEG file is stored as-is | |
JPXDecode | JPEG 2000 | either, by encoding choice | Photographs and scans needing better quality per byte | PDF 1.5 |
Crypt | Decryption hook, not compression | n/a | Per-stream encryption choices (see encryption) | PDF 1.5 |
Two details in the table matter in practice. DCTDecode describes the data as "image sample data that approximates the original", which is the specification's way of saying that a JPEG stays a JPEG: decoding and re-encoding it costs quality every time. And JBIG2Decode reproduces the original "or an approximation of that data", which is the clause behind the well-known cases where lossy JBIG2 symbol matching turned a 6 into an 8 on scanned documents. Scanners that use JBIG2 generic (lossless) mode are safe; the symbol-dictionary modes are a decision, not a default.
Filter chains and parameters#
A stream's /Filter entry is a name or an array of names. With an array, the filters were applied in sequence when the file was written and must be reversed in the order listed. ISO 32000-1 §7.4.1 gives the canonical example, a content stream that was LZW-compressed and then ASCII-85 encoded:
1 0 obj
<< /Length 534
/Filter [ /ASCII85Decode /LZWDecode ]
>>
stream
J..)6T`?p&<!J9%_[umg"B7/Z7KNXbN'S+,*Q/&"OLT'F
...
endstream
endobjThe reader decodes ASCII-85 first and feeds the binary result to the LZW decoder. Parameters, when a filter needs them, go in /DecodeParms, either one dictionary or an array parallel to the filter array.
For Flate and LZW the interesting parameter is /Predictor (Table 8). A predictor transforms each byte into the difference from a neighbour before compression, which makes image rows and cross-reference stream rows far more compressible. Values 10 to 15 select the PNG predictors (None, Sub, Up, Average, Paeth, or per-row choice), value 2 the TIFF predictor, and the companion keys /Colors, /BitsPerComponent and /Columns tell the decoder the row geometry. Cross-reference streams almost always use /Predictor 12 with /Columns equal to the entry width, which is why a hand-written parser that handles plain Flate still fails on them until it undoes the predictor. The xref page works through that case byte by byte.
A real file under qpdf#
The file below was generated with pdf-lib for this page: one page of text and one 96 × 64 pixel RGB image that started life as a 15,181-byte PNG. qpdf's JSON output (qpdf --json=2 file.pdf) lists every object with its stream dictionary. Summarised to one line per object:
obj type stream filter length notes
1 /Pages
2 /Catalog
3 (Info dictionary)
4 /Font /Type1
5 /Page
6 stream /FlateDecode 264 page content stream
7 /XObject /Image stream /FlateDecode 12790 96 x 64, 8 bpc, /DeviceRGB
8 /ObjStm stream /FlateDecode 466 object stream holding 5 objects
9 /XRef stream /FlateDecode 46 cross-reference stream, /W [1 2 2]Three things are visible here that a text editor would never show. The content stream is 264 bytes compressed. The image is stored as raw RGB samples (96 × 64 × 3 = 18,432 bytes) that Flate brought down to 12,790; the PNG container is gone, because PDF has no PNG filter, only Flate plus optional predictors. And objects 1 to 5 are not in the file as separate obj … endobj blocks at all: they live inside object stream 8, and the index that finds them is itself a Flate-compressed stream. Running qpdf --qdf --object-streams=disable file.pdf out.pdf unpacks all of that into a readable form:
%% Contents for page 1
%% Original object ID: 6 0
5 0 obj
<<
/Length 6 0 R
>>
stream
q
BT
0.07 0.07 0.1 rg
/Helvetica-7098480789 24 Tf
24 TL
1 0 0 1 72 770 Tm
(Stream filters demo) Tj
T*
ET
Q
...The same demonstration with a 3840 × 2400 JPEG added tells the other half of the story. pdf-lib wrote the JPEG's 680,031 bytes into the image stream unchanged, with /Filter /DCTDecode, and the file grew from 14 KB to 694 KB. Asking qpdf to recompress everything at maximum Flate level (--recompress-flate --compression-level=9 --object-streams=generate) produced a file of 694,476 bytes: 81 bytes larger, because Flate cannot compress JPEG data and the only streams it could touch were already tiny. That is the normal outcome for any file dominated by photographs, and the reason lossless tools are honest when they report "no change".
Why a compressed PDF is still large#
When a file is bigger than it should be, the cause is almost always one of these, in rough order of frequency:
- Images at the wrong resolution. A 12-megapixel photo placed into a 5 cm wide box still carries 12 megapixels. Nothing in the format downsamples automatically.
- Images in a lossless filter when they are photographs. Screenshot tools and some converters write Flate-compressed RGB, which is three to ten times larger than JPEG at a quality nobody can distinguish.
- Fonts embedded whole instead of subset. Each full OpenType font adds 100 KB to several MB; the fonts page explains subsetting and how to check it.
- Duplicate resources. The same logo embedded once per page, or the same font once per page, because the generator did not share objects. Common in merged documents.
- Incremental update history. Every save in a reader that appends rather than rewrites leaves the earlier revisions in the file. A form filled and saved twenty times carries twenty copies of its changed objects.
- Attachments, thumbnails, ICC profiles, XMP that nobody needs. Output intents with a 2 MB CMYK profile are a frequent surprise in print-ready files.
- No object streams and uncompressed structure. Measurable only on very long documents, but free to fix.
qpdf --json=2 combined with a few lines of script, or pdfimages -list from Poppler for the image inventory, answers which of these applies within seconds. The PDF inspector on this site reports the font list and embedding state in the browser.
What "compress PDF" tools really do#
The online services and the "Reduce File Size" commands in desktop software apply some combination of the following. Only the first group is lossless.
Lossless (safe to apply blindly): recompress Flate streams with a better encoder; move objects into object streams and use a cross-reference stream; remove unreferenced objects; drop incremental update history by rewriting the file; merge identical streams; strip thumbnails, metadata and private application data.
Lossy (quality decisions made for you): downsample images to a target resolution, typically 150 PPI or less; re-encode images as JPEG at a lower quality setting, including images that were already JPEG, which compounds artefacts; convert bilevel scans to lossy JBIG2; convert colour images to indexed colour; subset fonts (lossless for viewing, but it removes glyphs you would need to edit the text later); flatten annotations and form fields into page content.
A service that turns a 20 MB scan into 2 MB has downsampled and re-encoded the images. That may be exactly right for an email attachment and exactly wrong for a file going to a printer or an archive. The honest way to use these tools is to decide the target first: screen viewing at 100% zoom needs around 150 PPI; print needs 300 PPI at the placed size; archival under PDF/A should not be re-encoded at all. The DPI and resolution page gives the numbers.
Compressing properly from the command line#
Lossless clean-up with qpdf. This rewrites the file, which also discards incremental-update history and unreferenced objects:
# Recompress all Flate streams at maximum level, pack objects into object streams
qpdf --recompress-flate --compression-level=9 --object-streams=generate in.pdf out.pdf
# The same plus linearization for web viewing (page 1 loads before the rest downloads)
qpdf --recompress-flate --object-streams=generate --linearize in.pdf out.pdfMuPDF's mutool clean garbage-collects unused objects and recompresses:
# -g garbage collect, -gg also renumber, -ggg also merge duplicate objects; -z deflate streams
mutool clean -ggg -z in.pdf out.pdfGhostscript is the tool people reach for when they want smaller images, and it is important to understand what it does. The pdfwrite device does not edit the input; it interprets the PDF as if printing it and writes a new PDF of the result. Fonts can be re-encoded, colour converted, transparency flattened, and tagged structure, bookmarks or form fields may not survive. -dPDFSETTINGS selects a preset: /screen downsamples colour and grey images to 72 PPI, /ebook to 150 PPI, /printer and /prepress leave resolution at 300 PPI and differ in colour handling.
# Lossy: images downsampled to 150 ppi, output re-created by the interpreter
gs -sDEVICE=pdfwrite -dPDFSETTINGS=/ebook -dNOPAUSE -dBATCH -o out.pdf in.pdfUse it when you have decided that the images should be smaller and that the output is for reading, not for print production or archiving. Check the result: Ghostscript's own documentation notes that the presets alter the input and that the best fidelity comes from leaving -dPDFSETTINGS unset.
Coherent PDF's command-line tool has a lossless -squeeze that recompresses streams and removes redundancy, and separate image resampling options for the lossy step:
cpdf -squeeze in.pdf -o out.pdfDecompression as a hazard#
Because a Flate stream can expand a few kilobytes into gigabytes, any software that parses untrusted PDFs must bound the output of every decoder: a maximum decoded size per stream, a maximum image dimension, and a timeout. The same applies to nested filter chains and to object streams, which are decoded before the parser knows how many objects they contain. Libraries such as pdf.js, pypdf and qpdf carry limits of this kind; if you write a parser, copy the practice. The PDF inspector on this site stops inflating a stream past a fixed ceiling for exactly this reason.
Inspecting a file's filters#
# Every object with its filters, lengths and image geometry
qpdf --json=2 file.pdf
# Readable, uncompressed copy to open in a text editor
qpdf --qdf --object-streams=disable file.pdf readable.pdf
# Image inventory: filter, size in pixels, bits per component, placed resolution (Poppler)
pdfimages -list file.pdf
# Quick summary from MuPDF
mutool info -I file.pdfIf pdfimages -list shows photographs with enc image (Flate) rather than jpeg, or placed resolutions far above 300 PPI, you have found the bytes. If it shows nothing large and the file is still big, look at fonts next, then at the number of %%EOF markers, which counts the incremental updates.
Sources
- ISO 32000-1:2008, §7.4 Filters (§7.4.1 General, Table 6 Standard filters, §7.4.4 LZWDecode and FlateDecode, §7.4.4.4 Predictor functions, Tables 8 to 10, §7.4.5 to §7.4.10) PDF 1.7, distributed free of charge by Adobe
- ISO 32000-1:2008, §7.5.7 Object streams and §7.5.8 Cross-reference streams
- qpdf manual, command-line reference (--recompress-flate, --object-streams, --qdf, --json)
- Ghostscript documentation, "Vector devices" (pdfwrite, -dPDFSETTINGS)
- MuPDF, mutool clean
- Coherent PDF (cpdf) manual, -squeeze