Skip to content

PDF Compress — TypeScript source

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

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

// pdf-compress — second lib of the PDF trio (FEAT-035). Statically imports
// pdf-lib: only the islands' dynamic import keeps it out of the eager
// ToolRouter chunk (BUG-007 pattern; the perf budget's jsBytes line depends
// on it). Error types live in pdf-errors.ts (pdf-lib-free) so islands never
// need a static path into this module.
import { PDFDict, PDFDocument, PDFName, PDFNumber, PDFRawStream, PDFRef } from 'pdf-lib';
import { mapError, PdfToolError } from './pdf-errors';

export { PdfToolError, classifyLoadError, mapError } from './pdf-errors';

/** Why an embedded image was left untouched (null = it was recompressed). */
export type SkipReason = 'grew' | 'not-jpeg' | 'decode-failed';

/** Per-image outcome: before/after stream sizes, or why the original stayed. */
export type ImageAccounting = {
  /** Encounter order across all pages (0-based). */
  index: number;
  before: number;
  /** Recompressed size, or null when the original was kept. */
  after: number | null;
  skipped: SkipReason | null;
};

export type CompressResult = {
  bytes: Uint8Array;
  /** Number of embedded images examined (== images.length). */
  total: number;
  images: ImageAccounting[];
};

export type CompressOptions = {
  quality: number;
  /** Test seam: replaces the browser-only JPEG re-encoder (canvas). The
   *  default implementation is jsdom-unreachable by design — tests inject
   *  fakes to cover the walk's branches around it. */
  reencode?: (jpeg: Uint8Array, quality: number) => Promise<Uint8Array | null>;
};

/**
 * Pure decision: only baseline single-stream JPEGs are recompressible.
 * Anything else (Flate, multi-filter arrays like DCTDecode+FlateDecode,
 * no filter) is left byte-for-byte intact — we decode with the browser
 * image stack, which speaks bare JPEG only.
 */
export function chooseImageAction(dict: { filter: string }): 'skip' | 'recompress' {
  return dict.filter === 'DCTDecode' ? 'recompress' : 'skip';
}

/** Lossless metadata strip — title/author/subject/keywords/creator/producer. */
function stripMetadata(doc: PDFDocument): void {
  doc.setTitle('');
  doc.setAuthor('');
  doc.setSubject('');
  doc.setKeywords([]);
  doc.setCreator('');
  doc.setProducer('');
}

/**
 * Decode an embedded JPEG and re-encode it at `quality` at the SAME pixel
 * dimensions, via the browser's image stack (createImageBitmap + canvas).
 * Returns null when the platform can't decode (no createImageBitmap), can't
 * provide a 2d context, or the encode fails; throws when the decode itself
 * fails (corrupt bytes) — callers treat both as `decode-failed` and keep
 * the original. Dimensions are never changed, so page layout is untouched.
 */
/* v8 ignore next 29 — browser-only body (createImageBitmap + canvas); jsdom
   cannot execute it. The walk's branches around this helper are covered via
   the CompressOptions.reencode seam, and the typeof guard below IS covered
   (null path) by the no-createImageBitmap test. */
async function reencodeJpeg(jpeg: Uint8Array, quality: number): Promise<Uint8Array | null> {
  if (typeof createImageBitmap === 'undefined') return null;
  const bitmap = await createImageBitmap(new Blob([jpeg as BlobPart], { type: 'image/jpeg' }));
  const canvas: OffscreenCanvas | HTMLCanvasElement =
    typeof OffscreenCanvas !== 'undefined'
      ? new OffscreenCanvas(bitmap.width, bitmap.height)
      : Object.assign(document.createElement('canvas'), { width: bitmap.width, height: bitmap.height });
  const ctx = canvas.getContext('2d');
  if (!ctx) {
    bitmap.close();
    return null;
  }
  ctx.drawImage(bitmap, 0, 0);
  bitmap.close();
  const blob: Blob | null =
    canvas instanceof OffscreenCanvas
      ? await canvas.convertToBlob({ type: 'image/jpeg', quality })
      : await new Promise<Blob | null>((resolve) => canvas.toBlob(resolve, 'image/jpeg', quality));
  if (!blob) return null;
  return new Uint8Array(await blob.arrayBuffer());
}

/**
 * Two-pass, fully client-side PDF compression:
 *
 * Pass 1 (always): reload + save({ useObjectStreams: true }) + metadata
 * strip — the lossless floor. (No dedup claim: pdf-lib save has no
 * duplicate-object dedup API.)
 *
 * Pass 2 (only when quality < 1): walk every page's XObjects; each /Image
 * whose Filter is exactly DCTDecode is decoded and re-encoded at `quality`
 * at identical dimensions. A corrupt embedded JPEG never fails the run —
 * it is recorded as `decode-failed` and kept byte-for-byte. Re-encodes
 * that come out >= the original are recorded as `grew` and kept too.
 * SMask references, ColorSpace and dimensions stay untouched.
 */
export async function compressPdf(
  bytes: Uint8Array,
  opts: CompressOptions,
): Promise<CompressResult> {
  try {
    // Pass 1 — the lossless floor.
    const doc = await PDFDocument.load(bytes, { ignoreEncryption: false });
    stripMetadata(doc);
    let out = await doc.save({ useObjectStreams: true });

    // Pass 2 — JPEG recompression against the pass-1 output.
    const images: ImageAccounting[] = [];
    if (opts.quality < 1) {
      const pass2 = await PDFDocument.load(out, { ignoreEncryption: false });
      let index = 0;
      for (const page of pass2.getPages()) {
        // Untyped lookup + instanceof guard: pdf-lib's typed lookup(key, PDFDict)
        // THROWS when the key is merely absent — every Resources-less page
        // would crash the walk (caught by the weird-XObjects fixture).
        const xobjs = page.node.Resources()?.lookup(PDFName.of('XObject'));
        if (!(xobjs instanceof PDFDict)) continue;
        for (const [, value] of xobjs.entries()) {
          /* v8 ignore next 4 — guards against shapes no loadable PDF can
             carry: the PDF spec requires stream objects to be indirect, and
             pdf-lib prunes inline non-stream entries on save, so the non-ref
             and non-stream sides are unreachable through any load() input. */
          const ref = value instanceof PDFRef ? value : null;
          const stream = ref ? pass2.context.lookup(ref) : undefined;
          if (!(stream instanceof PDFRawStream)) continue;
          // Only /Image XObjects are accounted; form XObjects are ignored.
          if (stream.dict.get(PDFName.of('Subtype'))?.toString() !== '/Image') continue;
          const filter = stream.dict.get(PDFName.of('Filter'));
          const filterName =
            /* v8 ignore next 1 — multi-filter arrays (DCTDecode+FlateDecode):
               chooseImageAction already skips anything not exactly DCTDecode. */
            filter instanceof PDFName ? filter.toString().replace(/^\//, '') : (filter?.toString() ?? '');
          const before = stream.contents.length;
          if (chooseImageAction({ filter: filterName }) === 'skip') {
            images.push({ index: index++, before, after: null, skipped: 'not-jpeg' });
            continue;
          }
          let replacement: Uint8Array | null = null;
          try {
            replacement = await (opts.reencode ?? reencodeJpeg)(stream.contents, opts.quality);
          } catch {
            replacement = null; // corrupt embedded JPEG — never fail the run
          }
          if (!replacement) {
            images.push({ index: index++, before, after: null, skipped: 'decode-failed' });
          } else if (replacement.length >= before) {
            images.push({ index: index++, before, after: null, skipped: 'grew' });
          } else {
            stream.dict.set(PDFName.of('Length'), PDFNumber.of(replacement.length));
            pass2.context.assign(ref!, PDFRawStream.of(stream.dict, replacement));
            images.push({ index: index++, before, after: replacement.length, skipped: null });
          }
        }
      }
      out = await pass2.save({ useObjectStreams: true });
    }
    return { bytes: out, total: images.length, images };
  } catch (e) {
    mapError(e);
  }
}

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 →