DEV Community

Chris Howe
Chris Howe

Posted on

Before You Compress a PDF, Find Out What Is Actually Heavy

The build was green, the release notes were done, and the customer portal rejected the documentation PDF at 4:57 p.m. The file was only a manual, but suddenly it was the last unresolved dependency in the release.

Compression Starts With Classification

A PDF is a container, not an image format

The phrase “compress a PDF” sounds like a single operation. It is not. A PDF can contain text streams, embedded fonts, vector drawings, JPEG images, lossless images, annotations, forms, attachments, metadata, and several generations of incremental edits.

Two files can have the same page count and radically different size profiles. A 100-page API reference exported from a documentation generator may be mostly text and vector lines. A ten-page inspection report may contain ten full-resolution photographs. Rewriting both through the same pipeline is convenient, but convenience is not the same as correctness.

The first engineering decision should therefore be classification. You do not need a perfect semantic model of the document. You need enough evidence to choose a safe first strategy.

Three signals are usually enough for a useful preflight

The most practical signals are extractable text, embedded fonts, and page-sized images. Poppler gives us all three without requiring a custom PDF parser.

pdfinfo input.pdf
pdffonts input.pdf
pdftotext input.pdf -
pdfimages -list input.pdf
Enter fullscreen mode Exit fullscreen mode

If pdftotext returns substantial content and pdffonts lists fonts, the document probably has a useful text layer. If text output is nearly empty while every page contains one large image, it is probably scan-heavy. If both are present, it may be a mixed document or a scanned PDF with an OCR layer.

This is deliberately probabilistic. Some PDFs convert text to vector outlines. Some include a hidden OCR layer that is poor enough to be misleading. A preflight should produce a routing hint, not a courtroom verdict.

Do not classify from page one

Mixed documents are common in real workflows. The first page may be a generated cover, the next fifty pages may be scans, and the appendix may contain searchable tables. Looking only at the first page creates false confidence.

A small shell helper can sample representative pages and preserve the evidence in a build artifact.

#!/usr/bin/env bash
set -euo pipefail

file="${1:?usage: pdf-preflight input.pdf}"

pdfinfo "$file" | grep -E 'Pages|Page size|File size|PDF version'

printf '\nExtracted non-space characters: '
pdftotext "$file" - | tr -d '[:space:]' | wc -m

printf 'Embedded font rows: '
pdffonts "$file" | awk 'NR > 2 {count++} END {print count+0}'

printf '\nFirst image objects:\n'
pdfimages -list "$file" | sed -n '1,14p'
Enter fullscreen mode Exit fullscreen mode

This script is intentionally boring. Boring diagnostics are good diagnostics. It gives a human or CI job a compact snapshot before any destructive transformation happens.

Choose a Strategy That Preserves the Useful Properties

Structural optimization is the least dramatic path

For a text-heavy PDF, the safest first pass is usually structural cleanup. That may include object-stream compression, removal of unreachable objects, font subsetting, and consolidation of duplicate resources. The possible reduction is smaller than a full rasterization, but searchability, selectable text, vector graphics, and accessibility information have a better chance of surviving.

Tools such as qpdf are useful for normalization and stream compression, but they cannot magically shrink image data that is already stored as compressed JPEG bytes. This is a useful boundary to understand. A command can rewrite a PDF cleanly and still produce only a modest size difference.

Image-heavy documents need image decisions

When photographs or page scans dominate the file, the largest gains usually come from downsampling and re-encoding those images. That introduces questions a generic “compress” function cannot answer on its own.

What is the destination? A screen-only review copy does not need the same effective resolution as a print master. Does color carry meaning? A photographed receipt may tolerate grayscale; a heat map may not. Are the images natural photographs or interface screenshots? JPEG can work well for the former and create ugly halos around the latter.

The correct quality setting is contextual. It should be selected from the document's use, not copied from a random code snippet.

Rasterizing every page is a trade, not a free win

Rendering each page to a bitmap and rebuilding the PDF is tempting because it turns a complex object graph into a predictable sequence of images. It can also remove searchable text, links, form fields, vector sharpness, tags, and semantic structure.

Sometimes that trade is acceptable. A scan-only sharing copy already behaves like an image collection. For a technical manual with code samples, searchable headings, and internal links, the same approach may solve the size problem by damaging the document's most useful features.

This is why a compression service should not be evaluated only by the final byte count. The file is smaller, but is it still the same kind of tool for the reader?

Build Validation Into the Pipeline

A successful process exit is not a successful document

PDF processors are often treated like compilers: if the command exits successfully, the output is accepted. That is not enough. A valid PDF can still have missing pages, unreadable small text, broken links, duplicated OCR layers, or an output size larger than the input.

A minimal validation step should compare page count, page dimensions, file size, and extractable text. It should also render a small set of pages to images for visual review.

pdfinfo input.pdf  > before.info
pdfinfo output.pdf > after.info

pdftotext input.pdf  before.txt
pdftotext output.pdf after.txt

pdftoppm -f 1 -l 1 -png -r 144 output.pdf preview-first
Enter fullscreen mode Exit fullscreen mode

For a large document, include one ordinary body page, one image-heavy page, and one page with tables or small labels. Random sampling is useful, but risk-based sampling is better.

Refuse output that is worse than the input

Compression can occasionally increase file size. A tiny text PDF may grow after its pages are rendered as images. An already optimized document may gain overhead when rewritten. A production pipeline should compare sizes and decline to publish the candidate when there is no meaningful improvement.

That rule sounds obvious, yet it is often missing because the team focuses on whether transformation completed. “No improvement” is a valid result. Returning the original file is better than confidently delivering a larger one.

Keep a master and produce a delivery copy

The safest workflow does not ask one file to satisfy every purpose. Keep the original or a high-quality master for editing, archiving, and printing. Produce a separate delivery copy for email, upload portals, mobile reading, or chat.

That separation changes the discussion. You are no longer deciding whether to permanently degrade the only copy. You are creating an output optimized for a known destination while preserving the source of truth.

Decide When Automation Is Worth It

One blocked upload does not require a platform

If the problem is a single PDF and the deadline is now, building a local processing stack is probably the wrong optimization. A browser-based option such as PDFCompress can handle the delivery copy while leaving the engineering environment alone. The useful habit is still the same: keep the original and inspect the result on the device or portal that will receive it.

The product mention belongs here because this is the point where engineering judgment meets operational reality. Not every file problem deserves new code.

Repetition is the signal to automate

Automation becomes valuable when the same source produces the same failure repeatedly. If a reporting system exports image-heavy PDFs every morning, build preflight, transformation, validation, and fallback into the job. Record the input size, output size, page count, selected strategy, and validation result.

Those measurements turn “PDF compression” from a mysterious button into an observable pipeline. They also make regressions visible. If a template change causes reports to double in size, the team can see the shift before users encounter an upload error.

The best default is a reversible decision

There is no universal compression preset because there is no universal PDF. A useful system makes the least destructive change that meets the destination constraint, verifies the result, and keeps the source available.

The release manual that failed at 4:57 p.m. did not need a heroic algorithm. It needed a smaller delivery copy and a workflow that would prevent the same surprise next week.

That is the broader lesson. Compression is not the final step after the “real work.” The moment a document must move between systems and people, delivery becomes part of the engineering.

Top comments (1)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.