DEV Community

Gingertool
Gingertool

Posted on AI-assisted

Compressing PDFs Entirely in the Browser with pdf.js and pdf-lib

Many "compress PDF" sites upload your file, run it through a server-side tool such as Ghostscript and send the result back. For scans of passports, contracts and medical letters, that upload is the part people would rather skip.

We built a PDF compressor for Gingertool that never uploads anything. This post walks through how it works, the numbers we picked, and the trade-offs you accept when you compress on the client.

The approach: rasterize, re-encode, rebuild

There is no Ghostscript in the browser (not without a heavy WASM build and an AGPL licence question). So instead of rewriting the PDF's internal streams, we take a simpler route:

  1. Load the PDF with pdf.js.
  2. Render each page to a <canvas> at a chosen scale.
  3. Encode the canvas as JPEG at a chosen quality.
  4. Rebuild a new PDF with pdf-lib: one page per original page, same physical size, with the JPEG drawn full-bleed.

This is the core loop, simplified:

import { PDFDocument } from 'pdf-lib';
import * as pdfjs from 'pdfjs-dist/legacy/build/pdf.mjs';

async function compressPdf(bytes, { scale, quality }) {
  const src = await pdfjs.getDocument({ data: bytes, isEvalSupported: false }).promise;
  const out = await PDFDocument.create();

  for (let n = 1; n <= src.numPages; n++) {
    const page = await src.getPage(n);
    const base = page.getViewport({ scale: 1 });          // size in PDF points
    const viewport = page.getViewport({ scale });

    const canvas = document.createElement('canvas');
    canvas.width = Math.floor(viewport.width);
    canvas.height = Math.floor(viewport.height);
    const ctx = canvas.getContext('2d');
    ctx.fillStyle = '#fff';                                // see "gotchas" below
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    await page.render({ canvasContext: ctx, viewport }).promise;

    const blob = await new Promise((r) => canvas.toBlob(r, 'image/jpeg', quality));
    const jpg = await out.embedJpg(new Uint8Array(await blob.arrayBuffer()));

    const outPage = out.addPage([base.width, base.height]); // keep physical size
    outPage.drawImage(jpg, { x: 0, y: 0, width: base.width, height: base.height });

    page.cleanup();
    canvas.width = canvas.height = 0;                      // free GPU memory early
  }

  await src.destroy();
  return out.save();
}
Enter fullscreen mode Exit fullscreen mode

Choosing scale and quality

A PDF page is measured in points, 72 per inch. Rendering at scale = 1 gives you 72 dpi, so the scale maps directly to resolution:

Level Scale ≈ dpi JPEG quality
Light 1.25 90 0.78
Balanced 1.10 79 0.62
Strong 0.90 65 0.48

We tuned these for reading on a screen, not for printing. Around 80–90 dpi keeps body text legible for an emailed form or an uploaded receipt. Strong exists for hard portal limits (a 2 MB cap, say): headings survive, but fine print and small table numbers get soft. The UI shows a preview so people can zoom in before downloading.

Gotchas we hit

1. Transparent areas turn black. JPEG has no alpha channel. If you render onto a transparent canvas and export to JPEG, anything not painted comes out black. Filling the canvas white before page.render() fixes it.

2. iOS Safari's canvas limit. Safari caps a single canvas at roughly 16.7 million pixels. A large-format page (an A1 drawing, a long receipt) at scale 1.25 can blow past that and silently render nothing. We clamp each page to 14M pixels with a fit factor:

const MAX_PAGE_PIXELS = 14_000_000;
const fit = Math.min(1, Math.sqrt(MAX_PAGE_PIXELS / (base.width * base.height * scale ** 2)));
const viewport = page.getViewport({ scale: scale * fit });
Enter fullscreen mode Exit fullscreen mode

3. Memory on long documents. Releasing each canvas (width = height = 0) and calling page.cleanup() inside the loop keeps a 300-page scan from exhausting memory on a phone. It's still slow on older phones, so we report progress per page.

4. Encrypted and broken files. pdf.js throws a PasswordException for encrypted PDFs. We map that and any other load failure to clear error codes (ENCRYPTED, INVALID_FILE) so the UI can explain what happened instead of showing a stack trace.

The trade-offs (be upfront about them)

Rasterizing is not free:

  • Text stops being text. The output is images, so text is no longer selectable or searchable. For a scanned certificate that's fine; it was an image already. For a typed resume, it's a loss.
  • Text-only PDFs may get bigger. A vector page with a few KB of text becomes a JPEG of tens of KB. When the output isn't smaller, the UI says so instead of handing back a bigger file.
  • Links, form fields and bookmarks are gone. Only the visual page survives.

So client-side rasterizing is the right tool for scans and photo-heavy PDFs, which is exactly what people are trying to email or upload when they hit a size limit. For text-heavy PDFs, the honest advice is "you probably don't need to compress this".

Why bother doing it client-side?

  • Privacy you can verify. Open DevTools → Network while it runs: no request carries the file.
  • No upload wait. A 20 MB scan on a slow connection takes longer to upload than to process locally.
  • Cheap to run. Static hosting, no processing servers, no file retention policy to write.

If you want to see it in action, the compressor is live at gingertool.com/en/pdf/compress-pdf. Questions about the pdf.js setup (worker loading, CMaps for CJK fonts) are welcome in the comments.

Top comments (0)