Skip to content

PDF Compress — JavaScript source

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

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

// pdf-compress — two-pass, fully client-side PDF compression with pdf-lib
// (npm), the plain-JS twin of src/lib/pdf-compress.ts: pass 1 strips
// metadata and re-saves with object streams (the lossless floor); pass 2
// re-encodes baseline JPEGs (/DCTDecode) at a lower quality via the browser
// canvas, at identical pixel dimensions so page layout is untouched.
import { PDFDict, PDFDocument, PDFName, PDFNumber, PDFRawStream, PDFRef } from 'pdf-lib';

/** Load failure kind: 'encrypted' (password-protected) or 'invalid' (unparseable). */
export class PdfToolError extends Error {
  constructor(code, message) {
    super(message);
    this.code = code;
  }
}

/** Pure classifier — encrypted vs invalid, from the raw error message. */
export function classifyLoadError(msg) {
  return msg && /encrypt|password/i.test(msg) ? 'encrypted' : 'invalid';
}

/** Map a thrown load/parse error to a user-facing PdfToolError. */
function mapError(e) {
  const msg = e instanceof Error ? e.message : String(e);
  const kind = classifyLoadError(msg);
  throw new PdfToolError(
    kind,
    kind === 'encrypted'
      ? 'This PDF is password-protected. Unlock it first.'
      : 'Not a readable PDF file.',
  );
}

/** Per-image outcome: before/after stream sizes, or why the original stayed. */
// ImageAccounting = { index, before, after: number|null,
//                     skipped: 'grew'|'not-jpeg'|'decode-failed'|null }

/**
 * Pure decision: only baseline single-stream JPEGs (/Filter /DCTDecode) are
 * recompressible — the browser image stack speaks bare JPEG only.
 */
export function chooseImageAction(dict) {
  return dict.filter === 'DCTDecode' ? 'recompress' : 'skip';
}

/** Lossless metadata strip — title/author/subject/keywords/creator/producer. */
function stripMetadata(doc) {
  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. Returns null when the platform can't decode or encode; throws
 * when the decode itself fails (corrupt bytes) — callers treat both as
 * `decode-failed` and keep the original.
 */
async function reencodeJpeg(jpeg, quality) {
  if (typeof createImageBitmap === 'undefined') return null;
  const bitmap = await createImageBitmap(new Blob([jpeg], { type: 'image/jpeg' }));
  const canvas =
    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 =
    canvas instanceof OffscreenCanvas
      ? await canvas.convertToBlob({ type: 'image/jpeg', quality })
      : await new Promise((resolve) => canvas.toBlob(resolve, 'image/jpeg', quality));
  if (!blob) return null;
  return new Uint8Array(await blob.arrayBuffer());
}

/**
 * Pass 1 always runs (the lossless floor). Pass 2, only when quality < 1,
 * walks each page's 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 >= the original are kept as `grew`.
 */
export async function compressPdf(bytes, opts) {
  try {
    const doc = await PDFDocument.load(bytes, { ignoreEncryption: false });
    stripMetadata(doc);
    let out = await doc.save({ useObjectStreams: true });

    const images = [];
    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: the typed lookup THROWS when the
        // key is merely absent — every Resources-less page would crash the walk.
        const xobjs = page.node.Resources()?.lookup(PDFName.of('XObject'));
        if (!(xobjs instanceof PDFDict)) continue;
        for (const [, value] of xobjs.entries()) {
          const ref = value instanceof PDFRef ? value : null;
          const stream = ref ? pass2.context.lookup(ref) : undefined;
          if (!(stream instanceof PDFRawStream)) continue;
          if (stream.dict.get(PDFName.of('Subtype'))?.toString() !== '/Image') continue;
          const filter = stream.dict.get(PDFName.of('Filter'));
          const filterName =
            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 = null;
          try {
            replacement = await 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 →