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

Compressing a PDF to under 200 KB in the browser, with no server

Government forms, university portals and visa applications in a lot of countries ask for a PDF "under 200 KB". What people do next is upload their ID scans, certificates and bank statements to whatever free compressor ra

Government forms, university portals and visa applications in a lot of countries ask for a PDF "under 200 KB". What people do next is upload their ID scans, certificates and bank statements to whatever free compressor ranks first that day.

I wanted to build the version that doesn't need the upload: the whole thing in the browser, the file never leaving the device. Here is what that actually takes, including the part I got wrong on the first pass.

No server means no Ghostscript

Server-side PDF compression is basically a wrapper around Ghostscript or qpdf. In a browser you have neither. What you do have:

  • pdf-lib — parse and write PDF structure
  • pdf.js — render a page to a canvas
  • canvas.toBlob() — encode that canvas as JPEG

That's the whole toolbox, and it gives you exactly two strategies.

Strategy 1: the free win — re-save the structure

Before touching image quality, just re-save the document with object streams. pdf-lib rewrites the cross-reference table and drops unreferenced objects. Nothing about the rendered page changes, and the text stays selectable.

async function structuralOptimize(file: File) {
  const doc = await PDFDocument.load(await file.arrayBuffer());
  return doc.save({ useObjectStreams: true });
}

For PDFs exported by Word, or produced by phone scanner apps that leave a lot of junk behind, this alone often lands under the limit. Always try it first — it costs one pass and loses nothing.

Strategy 2: when that isn't enough, rasterize

Render each page to a canvas, JPEG-encode it, embed it back as a single image per page:

for (let i = 1; i <= src.numPages; i++) {
  const { canvas, widthPt, heightPt } = await renderPage(src, i, scale);
  const jpg = await canvasToJpeg(canvas, quality);
  const img = await out.embedJpg(await jpg.arrayBuffer());
  out.addPage([widthPt, heightPt])
     .drawImage(img, { x: 0, y: 0, width: widthPt, height: heightPt });
  canvas.width = canvas.height = 0; // drop the bitmap before the next page
}

That last line matters more than it looks. A 40-page scan at scale: 2 holds a lot of bitmap memory, and on mobile Safari you will hit a wall well before page 40 if you keep every canvas alive. Zeroing the dimensions lets the backing store go.

The honest cost of this strategy: the text is no longer text. It's pixels. No selecting, no searching, no screen readers. For a scanned certificate that was already an image, you lose nothing. For a text PDF, you've just made it worse in a way the file size won't tell you about.

Strategy 3: hitting an exact target — don't walk the ladder

Now the actual problem: the user doesn't want "smaller", they want "≤ 200 KB".

The obvious loop is to try settings from gentlest to strongest and stop at the first that fits:

const targetLadder = [
  { scale: 2,    quality: 0.8  },
  { scale: 1.5,  quality: 0.65 },
  { scale: 1.1,  quality: 0.45 },
  { scale: 0.9,  quality: 0.4  },
  { scale: 0.75, quality: 0.35 },
  { scale: 0.6,  quality: 0.3  },
  { scale: 0.5,  quality: 0.25 },
];

Seven settings means up to seven full re-renders of every page. On a 20-page scan that's a long time to stare at a progress bar.

But output size along that ladder is monotonic — gentler settings never produce a smaller file than stronger ones. So it's a sorted array, and you can binary-search it:

let lo = 0, hi = targetLadder.length - 1;
let best: Uint8Array | null = null;

while (lo <= hi) {
  const mid = (lo + hi) >> 1;
  const raster = await rasterize(file, targetLadder[mid]);

  if (raster.length <= targetBytes) {
    best = raster;   // fits — try to do better
    hi = mid - 1;
  } else {
    lo = mid + 1;    // too big — go stronger
  }
}

ceil(log2(8)) = 3 renders instead of up to 7. And because it keeps narrowing downward after a hit, what you end up with is the gentlest setting that fits, not merely the first one that happened to.

Worth being precise about the monotonicity assumption: it holds for scale-and-quality pairs that both decrease, which is why the ladder moves both knobs in the same direction. If you let scale drop while quality rises, the array is no longer sorted and the binary search is wrong.

The part I got wrong: pretending it always works

The first version returned the smallest output it managed to produce and called it done. That's a lie in a specific, annoying case: a 30-page scan does not fit into 200 KB at any setting on that ladder. The user gets a file, believes it worked, and finds out at the upload form.

So the result carries whether it actually made it:

interface CompressResult {
  bytes: Uint8Array;
  method: "structure" | "raster";
  fits: boolean;
}

When fits is false, the UI shows the real size it reached and suggests splitting the document or removing pages instead. A tool that says "done!" over a 310 KB file, against a form that caps at 200 KB, has just moved the failure somewhere less convenient.

Same principle applies to reporting: show the output's measured size, never the size you were aiming for.

What I'd tell anyone building this

  • Try lossless structural optimization first, every time.
  • Rasterizing is a real trade, not a setting. Surface it.
  • Binary-search the quality ladder; don't walk it.
  • Free each canvas as you go, or mobile will kill the tab.
  • Measure the output. Report what you got, including failure.

The finished tool is here if you want to throw a file at it: Compress PDF to 200KB. It's free, there's no signup, and the PDF is processed in your browser rather than uploaded — which was the entire point of the exercise.

Happy to hear how others have approached the target-size problem, especially anyone who found a way to keep text selectable while still hitting a hard byte limit.

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