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

How I compress PDFs entirely in the browser (no server, no uploads)

Most "compress PDF" websites work the same way: you upload your file, a server runs Ghostscript on it, and you download the result. That works, but it means a stranger's server gets a copy of your bank statement, your co

Most "compress PDF" websites work the same way: you upload your file, a server runs Ghostscript on it, and you download the result. That works, but it means a stranger's server gets a copy of your bank statement, your contract or your passport scan.

When I built PDFs Tools, I wanted every tool to run inside the browser instead. Nothing is uploaded, so there is nothing to leak, no file size limit to enforce and no server bill that grows with every user.

Compression was the hardest tool to get right. Here's the approach that works.

Why PDFs are big in the first place

Open a 12 MB PDF and look inside, and you'll almost always find the same thing: images. Scans, phone photos and screenshots saved at full resolution, often 3000–4000 px wide, embedded in a document that will only ever be viewed at a fraction of that size.

Text, fonts and vector graphics are usually a tiny part of the file. So the real job of a PDF compressor is simple to describe:

  1. Find every image in the PDF.
  2. Downscale it to a sensible resolution.
  3. Re-encode it at a reasonable JPEG quality.
  4. Put it back, but only if the new version is actually smaller.

Text stays as text, so it remains sharp and selectable.

The tools: pdf-lib + the Canvas API

You don't need WebAssembly or a port of Ghostscript for this. Two things already available in the browser cover most of it:

  • pdf-lib to read and rewrite the PDF's internal objects.
  • The Canvas API (createImageBitmap, drawImage, canvas.toBlob) to decode, resize and re-encode images.

The nice trick: images stored with the DCTDecode filter are plain JPEG bytes. The browser can decode them directly, with no PDF renderer involved.

The code

Here's a simplified version of the core loop:

import { PDFDocument, PDFName, PDFRawStream, PDFArray } from 'pdf-lib';

const N = (name) => PDFName.of(name);

function isJpegImage(dict) {
  if (dict.get(N('Subtype')) !== N('Image')) return false;
  const filter = dict.get(N('Filter'));
  if (filter === N('DCTDecode')) return true;
  // Filter can also be an array: [/DCTDecode]
  return filter instanceof PDFArray &&
    filter.size() === 1 &&
    filter.get(0) === N('DCTDecode');
}

export async function compressPdf(file, { maxSide = 1600, quality = 0.7 } = {}) {
  const pdf = await PDFDocument.load(await file.arrayBuffer());
  const ctx = pdf.context;

  for (const [ref, obj] of ctx.enumerateIndirectObjects()) {
    if (!(obj instanceof PDFRawStream) || !isJpegImage(obj.dict)) continue;

    // CMYK JPEGs need colour conversion; skip them in this simple version
    if (obj.dict.get(N('ColorSpace')) === N('DeviceCMYK')) continue;

    // 1. Decode the original JPEG bytes
    const bitmap = await createImageBitmap(
      new Blob([obj.contents], { type: 'image/jpeg' })
    );

    // 2. Downscale so the longest side is at most maxSide
    const scale = Math.min(1, maxSide / Math.max(bitmap.width, bitmap.height));
    const w = Math.round(bitmap.width * scale);
    const h = Math.round(bitmap.height * scale);

    const canvas = document.createElement('canvas');
    canvas.width = w;
    canvas.height = h;
    canvas.getContext('2d').drawImage(bitmap, 0, 0, w, h);
    bitmap.close();

    // 3. Re-encode as JPEG
    const blob = await new Promise((resolve) =>
      canvas.toBlob(resolve, 'image/jpeg', quality)
    );
    const bytes = new Uint8Array(await blob.arrayBuffer());

    // 4. Only replace the image if we actually saved space
    if (bytes.length >= obj.contents.length) continue;

    const dict = obj.dict;
    dict.set(N('Width'), ctx.obj(w));
    dict.set(N('Height'), ctx.obj(h));
    dict.set(N('ColorSpace'), N('DeviceRGB')); // canvas always outputs RGB
    dict.set(N('BitsPerComponent'), ctx.obj(8));
    dict.set(N('Filter'), N('DCTDecode'));
    dict.delete(N('DecodeParms'));
    dict.delete(N('Decode'));

    ctx.assign(ref, PDFRawStream.of(dict, bytes));
  }

  return pdf.save({ useObjectStreams: true });
}

A few things worth pointing out:

  • Replace in place. Pages reference images by object number, so swapping the stream behind the same ref means no page content needs to change. The image is drawn at the same size on the page, just with fewer pixels behind it.
  • Never make things worse. Some JPEGs are already well compressed. If the new bytes aren't smaller, keep the original.
  • Fix the colour space. A canvas always gives you RGB, so a grayscale or ICC-based original needs its ColorSpace updated, or viewers will draw garbage.
  • Transparency survives. Soft masks (SMask) are separate objects, and the PDF spec allows a mask with a different resolution from its image, so they keep working.

What this simple version doesn't handle

To be honest about the limits:

  • Images that aren't JPEGs. Many PDFs store images with FlateDecode (PNG-style compression). Their bytes aren't something the browser can decode on its own, so you need pdf.js to render or decode them first.
  • CMYK images. Print-ready PDFs often use CMYK. Converting to RGB properly takes more care than a canvas gives you for free.
  • Huge files on phones. Decoding a 50-page scan holds a lot of bitmaps in memory. Processing images one at a time and calling bitmap.close() helps a lot.
  • Text-only PDFs. A PDF exported from Word is already small. There's simply no image data to squeeze, so expect only small gains there.

Hitting a target size

People rarely want "smaller". They want "under 500 KB because the upload form says so". A practical way to handle that is to run the compressor again with lower maxSide and quality values until the output fits, then stop at the first setting that works. That keeps as much quality as the limit allows.

Why bother doing it client-side?

  • Privacy. The file never leaves the device. That matters for exactly the documents people most often need to shrink: IDs, payslips, contracts and medical letters.
  • Speed. No upload or download wait. A 20 MB scan starts processing immediately.
  • Cost. The user's CPU does the work, so a free tool can stay free.

If you want to see it in action, the compressor is live at pdfs-tools.com/compress-pdf. Open your browser's network tab while it runs and you'll see your PDF never gets sent anywhere.

I'd love to hear how others handle FlateDecode images and CMYK in the browser. Let me know in the comments.

📰 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.