Hitting an Exact File Size When Compressing PDFs in the Browser
How I make a PDF land just under a size limit (like 200 KB) entirely client-side, without re-encoding every image a dozen times.
Most PDF compressors give you a slider: Light, Medium, Strong. You pick one, you get whatever size comes out. That's fine until a form says "maximum 200 KB". Then "Strong" gives you 340 KB, "Extreme" gives you 90 KB of mush, and you're back to guessing.
I build a set of PDF tools that run fully in the browser (nothing is uploaded), and the most common thing people ask them to do is hit a number. So the compressor has a target-size mode. This post is how it works, including the two versions that didn't.
The obvious approach, and why it's slow
Images are almost always where the bytes are. So the naive plan is:
- Re-encode every image at quality level N.
- Write the PDF and measure it.
- Too big? Go to N+1 and repeat.
On a 30-page phone scan, that's 30 JPEG encodes per attempt. Do that eight or ten times and a mid-range Android phone sits there for a minute. People close the tab.
Step 1: a ladder of settings
First, the settings themselves. Each rung is a resolution cap (in DPI, based on how big the image is actually drawn on the page), a separate cap for images that look like text, a JPEG quality and a maximum edge length:
export const IMAGE_LEVELS = [
{ dpi: 240, textDpi: 300, quality: 82, maxEdge: 3000 },
{ dpi: 200, textDpi: 300, quality: 76, maxEdge: 2400 },
{ dpi: 170, textDpi: 260, quality: 69, maxEdge: 2000 },
{ dpi: 144, textDpi: 225, quality: 62, maxEdge: 1650 },
{ dpi: 120, textDpi: 200, quality: 56, maxEdge: 1350 },
{ dpi: 96, textDpi: 170, quality: 50, maxEdge: 1100 },
{ dpi: 80, textDpi: 150, quality: 44, maxEdge: 900 },
{ dpi: 66, textDpi: 125, quality: 38, maxEdge: 700 },
];
For target mode, the ladder gets denser: two near-lossless rungs at the top for roomy targets, a halfway point between every pair of levels, and three last-resort rungs at the bottom (down to 42 DPI). About 20 rungs in all.
The separate textDpi matters more than it looks. A scanned certificate is mostly text, and text turns to fuzz long before a photo looks bad. Keeping text-like images sharper costs a few KB and saves the document.
Step 2: predict instead of encoding everything
The trick that made it fast: don't encode every image at every rung. Encode the three biggest images, and predict the rest.
const order = [...all].sort((a, b) => size(b) - size(a));
const sample = order.slice(0, Math.min(n, 3));
const rest = order.slice(sample.length);
const predict = async (rung: number) => {
await session.encode(rung, sample);
const sampleNew = session.imageBytes(rung, sample);
return nonImageBytes + sampleNew + restOriginal * (sampleNew / sampleOriginal); // scale the rest by the sample's ratio
};
The biggest images dominate the file, and images in one document tend to compress alike (same scanner, same camera, same content). So the ratio from three images is a good guess for the other twenty-seven.
Step 3: bisect the ladder
With a cheap predict(), finding the right rung is a binary search: find the gentlest setting predicted to fit.
const AIM = 0.965; // leave a little room: writing the file adds a few bytes
let lo = 0, hi = LADDER.length - 1;
while (lo < hi) {
const mid = (lo + hi) >> 1;
if ((await predict(mid)) <= maxBytes * AIM) hi = mid;
else lo = mid + 1;
}
Then encode every image once at that rung, write the file, and measure it for real. If it's still over (predictions can be a bit optimistic), step one rung stronger. In practice that's rare.
There's also an early exit. If even the strongest rung is predicted to be more than 15% over the target, images alone can't get there, so don't waste time encoding them.
Step 4: spend what's left
Bisection lands on a rung that fits, usually with some room to spare. A 200 KB target might come out at 171 KB. That leftover 29 KB is quality you could have kept.
So the last pass walks the images largest first and moves each one back up the ladder, one rung at a time, as long as the estimated total stays under the limit. The file ends up just under the target instead of comfortably under it, and the room goes to the images that benefit most.
Step 5: when images aren't the problem
Some PDFs are mostly text and vector drawings. There's nothing to squeeze. For those, there's an opt-in last resort: render each page to an image and rebuild the PDF from those (I call it flattening). It always reaches small targets, but the text stops being selectable, so it's off by default and the result says so.
// Method 1: images
if (analysis.images > 0) { /* ladder + bisection, as above */ }
// Method 2: flatten pages, only if the user allowed it
if (opts.allowRaster) { /* render pages at decreasing DPI until it fits */ }
// Otherwise: return the smallest result and say it didn't fit
If neither works, the tool returns the smallest file it managed and tells you plainly: couldn't shrink further - try allowing page flattening. A compressor that silently hands you a file that's still too big is worse than one that admits it.
What I'd tell my past self
- Hit the number, or say you didn't. People searching for a size are filling in a form with a hard limit. "Close" fails the form.
- Predict, then verify. Cheap estimates find the neighbourhood; one real encode confirms it.
- Aim slightly under. Writing the PDF adds overhead you can't predict exactly. 96.5% of the target is my margin.
- Text and photos need different floors. A 66 DPI photo is fine. A 66 DPI marksheet isn't.
If you want to see it working, I use exactly this pipeline for a 200 KB target on my site. Open DevTools while it runs: no request carries your PDF, because all of it happens on your device. (The only outside requests you will see are small anonymous analytics pings.)
Questions about the image encoding side (I re-encode with the browser's own canvas JPEG encoder, in parallel), happy to go deeper in the comments.
Comments
No comments yet. Start the discussion.