Dev.to WebDev 🛠 Dev 👁 0 📖 9 min read

A Reproducible PDF Compress Workflow for Email, Portals, and Web Delivery

A PDF can open perfectly on a developer’s laptop and still be a poor delivery asset. It may exceed an email attachment limit, fail an application portal, take too long to download on mobile, or contain far more image da

A PDF can open perfectly on a developer’s laptop and still be a poor delivery asset.

It may exceed an email attachment limit, fail an application portal, take too long to download on mobile, or contain far more image data than the reader needs.

A useful PDF compress workflow does not begin with the strongest preset. It begins with a delivery constraint: where the document is going, how large it may be, and which parts must survive processing.

This guide builds a repeatable workflow around source inspection, structural optimization, image downsampling, and output validation.

TL;DR

  • Keep the original PDF unchanged.
  • Define a measurable delivery target before compressing.
  • Inspect images, fonts, pages, and embedded objects.
  • Try a structural optimization pass before reducing image quality.
  • Generate separate candidates instead of repeatedly compressing one output.
  • Validate page count, text, links, forms, signatures, and visual clarity.
  • Leave headroom below hard upload limits.

Start with the delivery constraint

“Make the PDF smaller” is not a testable requirement.

“Keep the document below 9 MB while preserving readable charts, searchable text, and working links” is.

Different delivery cases need different trade-offs:

Delivery case Primary constraint What to verify
Email attachment Hard size limit Final size with safety margin
Application portal Size and format rules Page order, signatures, and required fields
Documentation download Transfer size Mobile loading and link behavior
Scanned archive Legibility Small text, stamps, and handwritten notes
Print handout Output quality Images, thin lines, and color
Long-term archive Source fidelity Preserve the untouched original

Write down the target before selecting a PDF compress setting. Otherwise, the process becomes a race toward the smallest number rather than a controlled delivery task.

Inspect the source before changing it

A PDF is a container. It may include text streams, fonts, JPEG images, lossless image data, vector graphics, annotations, forms, attachments, and metadata.

Page count alone does not explain file size. A 20-page scanned document can be much larger than a 200-page text report because every scanned page may be stored as a high-resolution image.

Poppler provides several useful inspection commands:

pdfinfo input.pdf
pdfimages -list input.pdf
pdffonts input.pdf

pdfinfo reports page count, page dimensions, encryption status, metadata, and total file size.

pdfimages -list helps answer questions such as:

  • How many raster images are embedded?
  • Are scanned pages stored at an unnecessarily high resolution?
  • Are images using JPEG, JPEG 2000, or lossless streams?
  • Does the document contain large color images that will only be viewed on a screen?

pdffonts shows which fonts are embedded and whether they are stored as subsets.

Also check the file’s internal consistency:

qpdf --check input.pdf

Do not begin a compression experiment with the only copy of an important document. Keep the source unchanged and write every candidate to a new file.

Estimate where the bytes come from

A useful first classification is:

Text-heavy PDF

These files contain searchable text, vector graphics, and relatively few images. They are often already compact.

Structural cleanup may reduce their size, but aggressive image settings will not help much because images are not the main source of data.

Image-heavy PDF

Brochures, exported presentations, and illustrated reports often contain large photographs or screenshots.

These files usually have more room for reduction, but image quality becomes the main constraint.

Scanned PDF

A scanned PDF may contain one full-page image per page. Text that appears selectable in some viewers may come from an OCR layer placed over those images.

Downsampling can save substantial space, but it may also make small print, stamps, signatures, or handwritten notes difficult to read.

Feature-rich PDF

Forms, annotations, layers, attachments, JavaScript, certificates, and digital signatures require extra care.

A PDF rewrite can preserve the visible pages while changing or removing behavior that matters to the workflow.

Try a structural pass first

Before reducing image resolution, try rewriting the PDF structure.

qpdf can generate object streams and recompress compatible Flate streams:

qpdf \
  --object-streams=generate \
  --recompress-flate \
  input.pdf \
  output-structural.pdf

This is a relatively conservative PDF compress pass because it does not deliberately downsample every embedded image.

Run another integrity check afterward:

qpdf --check output-structural.pdf

Compare the sizes:

ls -lh input.pdf output-structural.pdf

A text-heavy document may become smaller after structural optimization. A scanned document may barely change because most of its bytes are already stored inside compressed image streams.

A small reduction is still useful if the output remains functionally identical. Do not add quality loss when structural cleanup already meets the delivery requirement.

Use image downsampling only when justified

When images dominate the file, Ghostscript can produce a new PDF with recompressed and downsampled assets.

A practical starting candidate is the /ebook preset:

gs \
  -sDEVICE=pdfwrite \
  -dCompatibilityLevel=1.6 \
  -dPDFSETTINGS=/ebook \
  -dNOPAUSE \
  -dQUIET \
  -dBATCH \
  -sOutputFile=output-ebook.pdf \
  input.pdf

On Windows, the command may be named gswin64c instead of gs.

The preset is a starting point, not a promise of quality or final size. Ghostscript versions and source documents can behave differently.

Generate a candidate, then inspect it. Do not overwrite the source.

For documents containing screenshots, diagrams, or small text, pay particular attention to:

  • labels inside charts;
  • thin table borders;
  • syntax-highlighted code;
  • QR codes and barcodes;
  • stamps and signatures;
  • light gray text;
  • gradients and transparent elements.

A photo-heavy brochure may tolerate more image reduction than a scanned legal document.

Never compress the previous candidate again

Lossy processing is cumulative.

This sequence is risky:

original.pdf
  -> compressed-v1.pdf
  -> compressed-v2.pdf
  -> compressed-v3.pdf

Each version inherits the damage introduced by the previous pass.

Instead, create every candidate from the original:

original.pdf -> structural.pdf
original.pdf -> ebook.pdf
original.pdf -> stronger-test.pdf

This makes the comparison meaningful and prevents avoidable generational loss.

Build a small candidate matrix

A repeatable workflow records inputs, settings, and results.

Candidate Source Method Size Intended use
original.pdf Original None 24.8 MB Archive
structural.pdf Original qpdf rewrite 22.6 MB High-fidelity delivery
ebook.pdf Original Ghostscript /ebook 7.9 MB Email attachment
stronger-test.pdf Original More aggressive image settings 3.4 MB Portal upload test

The numbers above are examples, not expected compression ratios.

A good PDF compress result is the smallest candidate that still satisfies the actual delivery requirement. If the email limit is 10 MB and the 7.9 MB candidate looks correct, the 3.4 MB version may provide no practical benefit.

Validate with a small Python script

File size alone is not enough. At minimum, confirm that the page count remains stable and that text extraction still produces plausible output.

Install pypdf:

python -m pip install pypdf

Create validate_pdf.py:

from pathlib import Path
from pypdf import PdfReader
import sys

if len(sys.argv) != 3:
    raise SystemExit(
        "Usage: python validate_pdf.py original.pdf compressed.pdf"
    )

source_path = Path(sys.argv[1])
output_path = Path(sys.argv[2])

source = PdfReader(source_path)
output = PdfReader(output_path)

source_size = source_path.stat().st_size
output_size = output_path.stat().st_size
saved_percent = (1 - output_size / source_size) * 100

def extracted_chars(reader):
    total = 0

    for page in reader.pages:
        text = page.extract_text() or ""
        total += len(text)

    return total

source_chars = extracted_chars(source)
output_chars = extracted_chars(output)

print(f"Source size: {source_size / 1024 / 1024:.2f} MB")
print(f"Output size: {output_size / 1024 / 1024:.2f} MB")
print(f"Reduction: {saved_percent:.1f}%")
print(f"Source pages: {len(source.pages)}")
print(f"Output pages: {len(output.pages)}")
print(f"Source extracted characters: {source_chars}")
print(f"Output extracted characters: {output_chars}")

if len(source.pages) != len(output.pages):
    raise SystemExit("FAIL: page count changed")

if source_chars and output_chars < source_chars * 0.9:
    print("WARNING: extracted text changed significantly")

print("Automated checks completed; visual review is still required.")

Run it with:

python validate_pdf.py input.pdf output-ebook.pdf

Text extraction is not a complete accessibility or content test. Different PDF generators organize text differently, and some scanned documents contain no OCR layer.

The script is a signal, not proof.

Validate the real document behavior

Open the output in more than one PDF viewer when compatibility matters.

Check:

  • page count and page order;
  • searchable and selectable text;
  • bookmarks and table of contents;
  • internal and external links;
  • form fields and calculated values;
  • annotations and comments;
  • embedded attachments;
  • accessibility tags;
  • layers and optional content;
  • printing and print preview;
  • QR codes, barcodes, stamps, and signatures.

Digitally signed PDFs deserve special attention. Rewriting the file can invalidate an existing signature even when the visible pages appear unchanged.

If the signature must remain valid, do not process the signed document without understanding the signing workflow.

Leave headroom below hard limits

A portal that accepts files up to 10 MB should not receive a candidate that is exactly 10.00 MB.

Platforms may calculate megabytes differently, add transport overhead, or reject a file after additional processing.

Aim below the boundary:

Portal limit: 10 MB
Practical target: 9 MB or less

Unlike video encoding, PDF size does not map cleanly to one bitrate formula. A PDF may contain several unrelated data types, each responding differently to optimization.

That makes candidate generation and validation more reliable than pretending one setting can produce an exact byte count for every document.

Where a browser tool fits

A local workflow is preferable when compression must be automated, audited, or applied to confidential documents.

A browser workflow can still be useful for an occasional, non-sensitive file when no local PDF toolchain is available.

For example, the VideoCompress PDF compress tool currently provides a browser-based workflow with light, balanced, and strong compression levels. Its page also lists batch processing, PDF files up to 1 GB, and output without a watermark.

The site states that uploaded documents are automatically deleted within 24 hours. That does not replace an organization’s privacy, compliance, or data-residency requirements.

Use a non-sensitive sample, preserve the original, and apply the same validation checklist to the downloaded result.

The tool is an implementation option. The delivery constraint and verification process remain the same.

Common PDF compress mistakes

Starting with the strongest preset

The largest reduction percentage is not necessarily the best result. Start conservatively and stop when the file meets the real requirement.

Judging only the first page

A cover page may look perfect while a later scan, chart, or signature has become unreadable.

Recompressing an earlier output

Return to the original for every candidate. Do not build one lossy result from another.

Ignoring forms and links

A PDF can look correct while interactive behavior has changed.

Treating every PDF the same

Text reports, scans, brochures, slide exports, and signed forms have different risk profiles.

Targeting the exact upload ceiling

Leave a safety margin rather than relying on a boundary value.

Deleting the original

A delivery copy is not an archival source.

Pre-delivery checklist

  • [ ] The target platform and maximum file size are documented.
  • [ ] The untouched original is stored separately.
  • [ ] Page count, encryption, images, and fonts were inspected.
  • [ ] Structural optimization was tested before image degradation.
  • [ ] Every candidate was generated from the original.
  • [ ] The output has headroom below the platform limit.
  • [ ] Small text, charts, images, stamps, and QR codes were reviewed.
  • [ ] Links, bookmarks, forms, and attachments were tested.
  • [ ] Signature requirements were checked.
  • [ ] The file was opened in the real delivery environment.

Final thoughts

A reliable PDF compress workflow is a constraint-solving process, not a contest to create the smallest file.

Inspect the source. Define the destination. Try the least destructive change first. Generate each candidate from the original. Validate structure and visual quality. Then stop when the document is small enough to travel without losing the information that made it useful.

Once those decisions are written down, PDF delivery becomes repeatable instead of guesswork.

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.