Skip to content

PDF Compress — Python source

Shrink PDF file sizes in your browser — lossless optimization plus a JPEG quality slider for embedded images. Nothing uploads.

This is the Python implementation — the same logic the interactive tool runs, in a shareable, citable form.

# pdf-compress — two-pass PDF compression with pikepdf + Pillow. Authored
# snippet mirroring src/lib/pdf-compress.ts: pass 1 strips document metadata
# and re-saves with object streams (the lossless floor); pass 2 re-encodes
# baseline JPEG image XObjects (/Filter /DCTDecode) at a lower quality via
# Pillow, at identical pixel dimensions so page layout is untouched.
from __future__ import annotations

import io
from dataclasses import dataclass
from typing import List, Literal, Optional

import pikepdf
from PIL import Image

SkipReason = Literal["grew", "not-jpeg", "decode-failed"]


@dataclass
class ImageAccounting:
    """Per-image outcome: before/after stream sizes, or why the original stayed."""

    index: int
    before: int
    after: Optional[int]  # None when the original was kept
    skipped: Optional[SkipReason]


@dataclass
class CompressResult:
    data: bytes
    total: int
    images: List[ImageAccounting]


def choose_image_action(filter_name: str) -> str:
    """Pure decision: only baseline single-stream JPEGs (/DCTDecode) are
    recompressible — Pillow decodes bare JPEG only, mirroring the TS rule."""
    return "recompress" if filter_name == "DCTDecode" else "skip"


def strip_metadata(pdf: pikepdf.Pdf) -> None:
    """Lossless metadata strip — docinfo entries equivalent to the TS
    setTitle('')/setAuthor('')/... calls."""
    with pdf.open_metadata(set_pikepdf_as_editor=False) as meta:
        for key in (
            "dc:title",
            "dc:creator",
            "dc:description",
            "pdf:Keywords",
            "xmp:CreatorTool",
            "pdf:Producer",
        ):
            if key in meta:
                del meta[key]
    pdf.docinfo["/Title"] = pikepdf.String("")
    pdf.docinfo["/Author"] = pikepdf.String("")
    pdf.docinfo["/Subject"] = pikepdf.String("")
    pdf.docinfo["/Keywords"] = pikepdf.String("")
    pdf.docinfo["/Creator"] = pikepdf.String("")
    pdf.docinfo["/Producer"] = pikepdf.String("")


def _reencode_jpeg(raw: bytes, quality: float) -> Optional[bytes]:
    """Decode an embedded JPEG and re-encode it at `quality` at the SAME
    pixel dimensions. Returns None when Pillow can't decode/encode — callers
    treat that as `decode-failed` and keep the original."""
    try:
        with Image.open(io.BytesIO(raw)) as img:
            if img.mode not in ("RGB", "L"):
                img = img.convert("RGB")
            out = io.BytesIO()
            img.save(out, format="JPEG", quality=int(quality * 100), optimize=True)
            return out.getvalue()
    except Exception:
        return None


def compress_pdf(data: bytes, quality: float) -> CompressResult:
    """Pass 1 always runs (the lossless floor). Pass 2, only when
    quality < 1, walks each page's image XObjects: every /Image filtered
    exactly /DCTDecode is re-encoded at `quality`. A corrupt JPEG never
    fails the run — recorded as `decode-failed` and kept; re-encodes that
    came out >= the original are recorded as `grew` and kept too. SMask,
    ColorSpace and dimensions stay untouched."""
    with pikepdf.open(io.BytesIO(data)) as pdf:  # password=False refuses encrypted inputs
        strip_metadata(pdf)
        floor = io.BytesIO()
        pdf.save(floor, object_stream_mode=pikepdf.ObjectStreamMode.generate)
        if quality >= 1:
            return CompressResult(data=floor.getvalue(), total=0, images=[])

        with pikepdf.open(floor) as pass2:
            images: List[ImageAccounting] = []
            index = 0
            for page in pass2.pages:
                for name, obj in list(page.images.items()):
                    before = len(obj.read_raw_bytes())
                    if obj.Subtype != pikepdf.Name("/Image"):
                        continue
                    filt = obj.get("/Filter")
                    filter_name = str(filt).lstrip("/") if filt is not None else ""
                    if choose_image_action(filter_name) == "skip":
                        images.append(ImageAccounting(index, before, None, "not-jpeg"))
                        index += 1
                        continue
                    replacement: Optional[bytes] = None
                    try:
                        pdf_image = pikepdf.PdfImage(obj)
                        pil = pdf_image.as_pil_image()
                        buf = io.BytesIO()
                        if pil.mode not in ("RGB", "L"):
                            pil = pil.convert("RGB")
                        pil.save(buf, format="JPEG", quality=int(quality * 100), optimize=True)
                        replacement = buf.getvalue()
                    except Exception:
                        replacement = None  # corrupt embedded JPEG — never fail the run
                    if not replacement:
                        images.append(ImageAccounting(index, before, None, "decode-failed"))
                    elif len(replacement) >= before:
                        images.append(ImageAccounting(index, before, None, "grew"))
                    else:
                        page.images[name].write(
                            replacement,
                            filter=pikepdf.Name("/DCTDecode"),
                        )
                        images.append(ImageAccounting(index, before, len(replacement), None))
                    index += 1
            out = io.BytesIO()
            pass2.save(out, object_stream_mode=pikepdf.ObjectStreamMode.generate)
            return CompressResult(data=out.getvalue(), total=len(images), images=images)

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →