Every government portal, job site and university application seems to have the same rule: "Upload a PDF, max 200 KB." Then you scan a two-page form on your phone and get a 4 MB file.
I built KaiPDF, a free in-browser PDF toolkit; this is how one part of it works: the "make it smaller than X" mode of the compressor. Everything below runs in the browser tab. The file is never uploaded.
Why upload portals have size limits
The limits are rarely about the PDF itself. They come from older systems behind the form:
- Database blobs and mail gateways. Many back offices store attachments in a database column or forward them by email, where 200 KB to 2 MB was a safe number years ago.
- Bandwidth for reviewers. A clerk opening 500 applications a day doesn't want 5 MB each.
-
Defence against junk. A hard cap is the cheapest way to stop someone uploading a 300 MB video renamed to
.pdf.
So the limit is fixed and you can't argue with it. You just need the file under it, with the text still readable.
Why do it client-side
A size-limited upload is usually something personal: an ID card, a payslip, a medical form. Sending it to a third-party server to shrink it, so you can send it to the real server, is a strange trade.
The alternative is to bring the PDF engine to the file. KaiPDF ships two C/C++ libraries compiled to WebAssembly:
-
PDFium (Chrome's PDF engine, via
@embedpdf/pdfium) to open the file, find image objects, decode them and write new ones. -
qpdf (via
@neslinesli93/qpdf-wasm) to rewrite the file structure: object streams, Flate recompression, and dropping data nothing points to.
Both live in a dedicated Web Worker, so the page stays responsive while a 30-page scan is processed. The worker compiles each .wasm once and streams it while it downloads:
// src/lib/pdf/worker.ts (simplified)
async function compile(url: string): Promise<WebAssembly.Module> {
const res = await fetch(url);
try {
return await WebAssembly.compileStreaming(res.clone());
} catch {
// servers that send the wrong MIME type
return WebAssembly.compile(await res.arrayBuffer());
}
}
qpdf is a command-line program compiled with Emscripten. Its main() exits, so each run needs a fresh instance. Compiling is the slow part, so the worker keeps the compiled WebAssembly.Module and only instantiates a new copy per run. The PDF goes in through Emscripten's in-memory file system:
// src/lib/pdf/worker.ts (simplified)
mod.FS.writeFile('/in.pdf', input);
const code = mod.callMain([...args, '/in.pdf', '/out.pdf']);
// 0 = ok, 3 = finished with warnings (a damaged file that was fixed)
return mod.FS.readFile('/out.pdf');
Image encoding doesn't need a WASM codec at all. The worker draws the decoded pixels onto an OffscreenCanvas, scales them with imageSmoothingQuality = 'high', and calls convertToBlob({ type: 'image/jpeg', quality }). The browser's own JPEG encoder is fast and already there.
Where the bytes actually are
Before you compress anything, it helps to know what you are compressing. I split four test PDFs into image streams, font files, other streams (page content) and everything else (the object table, dictionaries, trailer):
| File | Total | Images | Fonts | Content + structure |
|---|---|---|---|---|
_photos.pdf (3 pages, 1 photo, 1 PNG with transparency) |
1,582 KB | 1,580 KB (99.8%) | 0 | 2.4 KB |
photo-report.pdf (5 pages, text + one phone photo each) |
4,608 KB | 4,602 KB (99.9%) | 0 | 6 KB |
scan.pdf (4 pages, full-page 300 dpi greyscale scans) |
2,268 KB | 2,266 KB (99.9%) | 0 | 2.6 KB |
text-30p.pdf (30 pages of plain text, standard font) |
83.7 KB | 0 | 0 | 83.7 KB |
This is typical. If a PDF is over a few hundred KB, it is almost always pictures. The photos in photo-report.pdf are 3840×2400 JPEGs placed about 7 inches wide, which is roughly 550 dpi on paper. Nobody needs that to read a form.
Fonts matter in some files (a full, unsubsetted CJK font can be several MB), but the compressor deliberately leaves them alone: removing glyphs safely needs to know every character the document will ever show. Text and vector drawings are never touched, so they stay sharp and selectable.
Step 1: a lossless pass
The first thing the target mode does is the free win. qpdf rewrites the file without changing a pixel:
qpdf(work, [
'--object-streams=generate', // pack small objects into compressed streams
'--compress-streams=y',
'--recompress-flate',
'--compression-level=9',
'--remove-unreferenced-resources=yes', // drop images/fonts no page uses
]);
On the 30-page text file this alone took it from 83.7 KB to 45.2 KB, because the original stored every dictionary as plain text. On the photo files it saved almost nothing (1–2 KB), which is the honest answer: you can't zip a JPEG.
If the lossless result is already under the target, we stop. No quality is lost.
Step 2: re-encoding images, one ladder step at a time
The lossy part re-encodes images inside the PDF at a given resolution and JPEG quality. It works per image object through PDFium:
- Measure how big the image is on the page (its bounds in points) and work out its effective DPI.
- Scale it down to the target DPI, never up.
- Encode as JPEG and swap it in with
EPDFImageObj_SetJpeg. - Regenerate the page content, save, and run qpdf so the old image data is dropped.
The settings come from a fixed ladder, from gentlest to harshest:
// src/components/tools/SimpleTools.tsx
const TARGET_STEPS = [
{ dpi: 144, quality: 0.66 },
{ dpi: 120, quality: 0.56 },
{ dpi: 96, quality: 0.46 },
{ dpi: 72, quality: 0.38 },
{ dpi: 56, quality: 0.3 },
{ dpi: 42, quality: 0.24 },
];
DPI and quality drop together on purpose. Lowering only the quality gives blocky artefacts long before the file gets small. Lowering only the resolution gives blur. Doing a bit of both stays readable for longer.
Searching the ladder by halving
Output size goes down as you go down the ladder, so you can binary-search it. We want the lightest step that fits, not the first one that fits:
// src/components/tools/SimpleTools.tsx
async function lightestFit(count, attempt, target) {
let lo = 0, hi = count - 1;
let fit = null, smallest = null;
while (lo <= hi) {
const mid = (lo + hi) >> 1;
const r = await attempt(mid);
if (!smallest || r.length < smallest.length) smallest = r;
if (r.length <= target) {
fit = r;
hi = mid - 1; // fits: try something gentler
} else lo = mid + 1; // too big: go harsher
}
return fit ? { bytes: fit, fits: true } : smallest && { bytes: smallest, fits: false };
}
With six steps it starts at step 2 (96 dpi) and needs at most three compressions instead of six. Each attempt starts from the original bytes, so quality loss never stacks up. If nothing fits, it still returns the smallest file it made, which matters for the next step.
Which images are skipped, and why
Not every image gets re-encoded. The loop in recompressImages (in src/lib/pdf/ops.ts) skips:
// simplified from src/lib/pdf/ops.ts
if (bpp <= 1 || w * h < 96 * 96) continue; // 1-bit scans, tiny icons
if (FPDFPageObj_HasTransparency(obj)) continue; // JPEG has no alpha
if (uses.get(signature) !== 1) continue; // shared images (logos on every page)
if (k2 > 0.85 && raw < outW * outH * 0.12 * (quality + 0.15)) continue; // already small
if (jpg.length >= raw * 0.9) continue; // re-encoding didn't help
- 1-bit images are usually black-and-white scans stored with CCITT or JBIG2, which are already tiny. JPEG would make them bigger and grey.
- Tiny images (under 96×96) aren't worth it.
- Images with transparency would lose their alpha channel and get a black or white box around them.
- Shared images. A first pass counts how often each image appears, using its size and a sampled hash of its raw bytes. A logo drawn on 40 pages is stored once, so re-encoding it per page would make 40 copies.
- Already efficient images, and any re-encode that saves less than 10%, are left as they are. That stops pointless quality loss.
In _photos.pdf, the 512×512 PNG has a soft mask, so it was skipped. Only the big photo was re-encoded (3840×2400 down to 960×600).
Step 3: the optional fallback, and telling the user
Some files can't get under the limit by shrinking pictures. A text-heavy PDF with no images is the obvious case. For those, there's a checkbox (on by default): "If needed, save pages as images to reach the size."
This mode renders each whole page to a JPEG with PDFium and replaces the page with that picture, using a second ladder (120 dpi down to 38 dpi), searched with the same lightestFit. It is lossy in a different way: the text is no longer selectable or searchable. So if this path wins, the result screen says exactly that: "To reach this size the pages were saved as images, so the text can no longer be selected."
It only wins if it actually beats the image-only result. If neither path reaches the target, the user gets the smallest file we made and a plain message that the target isn't reachable for this document, rather than a silent failure.
Measured results
I ran the same code on four PDFs: the exact recompressImages, rasterize, TARGET_STEPS, RASTER_STEPS and lightestFit from the repo, the same qpdf arguments and the same qpdf WASM build. The setup was Node 22 with tsx on an Intel Core i5-11300H laptop with 8 GB RAM. The one difference from the browser: in Node there's no OffscreenCanvas, so I used sharp (libjpeg-turbo) as the JPEG encoder. Browser sizes will differ by a few percent because every JPEG encoder differs.
Three of the files I generated with pdf-lib from stock Windows wallpapers; _photos.pdf is a test file from the project.
Target: 200 KB
| File | Before | After lossless pass | Final | Step used | Passes | Time |
|---|---|---|---|---|---|---|
_photos.pdf |
1,582 KB | 1,578 KB | 50.6 KB | 144 dpi, q 0.66 | 3 | 1.7 s |
photo-report.pdf |
4,608 KB | 4,606 KB | 93.5 KB | 144 dpi, q 0.66 | 3 | 5.3 s |
scan.pdf |
2,268 KB | 2,268 KB | 124.2 KB | 96 dpi, q 0.46 | 4 | 5.1 s |
text-30p.pdf |
83.7 KB | 45.2 KB | 45.2 KB | lossless only | 1 | 0.08 s |
"Passes" counts the lossless pass plus each ladder attempt. On scan.pdf the search went 96 dpi (124 KB, fits), then 144 dpi (347 KB, too big), then 120 dpi (208 KB, just over), so it kept 96 dpi.
Lower targets, to show the ladder moving:
| File | Target | Final | Step used |
|---|---|---|---|
_photos.pdf |
50 KB | 38.0 KB | 120 dpi, q 0.56 |
_photos.pdf |
25 KB | 21.9 KB | 72 dpi, q 0.38 |
photo-report.pdf |
50 KB | 42.6 KB | 96 dpi, q 0.46 |
photo-report.pdf |
25 KB | 18.5 KB | 56 dpi, q 0.3 |
scan.pdf |
100 KB | 67.5 KB | 72 dpi, q 0.38 |
scan.pdf |
25 KB | 22.8 KB | 42 dpi, q 0.24 |
text-30p.pdf |
25 KB | 45.2 KB (no fit) | none |
The last row is the interesting failure. The image ladder found nothing to shrink (no images). The page-as-image fallback then produced 2,220 KB, 790 KB and 365 KB at its three attempts. Thirty pages of crisp vector text are far smaller than thirty JPEGs of the same pages. So the code kept the 45.2 KB lossless file and told the user the target wasn't reachable. That is the right result, even if it isn't the one they wanted.
Limits and trade-offs
- "Exact" means "under", not "equal to". The ladder has six fixed steps, so the result often lands well below the target (93.5 KB for a 200 KB limit above). A finer search would get closer to the limit and keep a bit more quality, at the cost of more passes. I chose fewer, predictable passes.
- The ladder doesn't go gentler than 144 dpi. If 144 dpi fits with room to spare, you don't get a 200 dpi version. The fixed "Light" preset exists for that.
- Text-only files have a floor. If the lossless pass can't reach the target, nothing can without making it worse. Splitting the document is the real fix.
- Skipped images stay big. A huge PNG with transparency, or one big image shared across pages, is left alone. A file made mostly of those may not shrink much.
- Fonts aren't subset or removed. A PDF carrying a full embedded font keeps it.
- Rasterising loses text. It's opt-out, and the user is told when it happens, but a rasterised form can no longer be searched or read by a screen reader.
- It costs CPU and memory on the user's device. Each attempt decodes images at full size. A 4,000×3,000 photo is 48 MB of RGBA in memory. On a low-end phone a long, photo-heavy scan can be slow, and the work can't be offloaded.
- Encrypted PDFs need the password first; the engine can't work on what it can't decrypt.
Wrapping up
The core idea is small: do the free lossless pass first, then binary-search a joint DPI/quality ladder from the original bytes each time, skip the images where JPEG would do harm, and be honest when the only way down is turning pages into pictures. WebAssembly makes it possible to run the same well-tested C/C++ engines that desktop tools use, on files that never leave the device.
If you want to try it on your own file, the tool is at kaipdf.com/compress-pdf, and there is a page about reducing a PDF for online forms with the target mode preset.
Top comments (0)