DEV Community

Cover image for How I Compress PDFs in the Browser While Keeping Text Selectable
Asad Ali
Asad Ali

Posted on AI-assisted

How I Compress PDFs in the Browser While Keeping Text Selectable

Two 5 MB PDFs can look identical at page width. Try copying a part number. In a scanned manual, the letters may be pixels in a photograph. In a report exported from a word processor, an embedded font can draw the same letters as selectable glyphs.

I built the browser PDF compressor around that distinction. Both modes start with a worker that optimises existing PDF objects. Choosing Extreme allows a second pass that renders whole pages if the first pass misses the byte budget.

What Smart mode can shrink

A PDF page can draw an image by referring to a separate object that contains the encoded pixels. That indirection gives the compressor a useful place to intervene. If a report includes a three-megapixel photograph displayed at the width of a business card, a smaller JPEG can occupy the same rectangle. The caption beneath it still uses the original text operators and font.

The worker loads the document with pdf-lib, discards selected metadata and thumbnails, collects unreachable objects and merges byte-identical streams. Consider a logo that an exporter embedded afresh on every page. Pointing those references to one copy saves space without degrading the logo. The worker also trims excess decimal precision in supported drawing streams. Even a document with no photographs can benefit from these steps.

For images, the worker recognises a limited set of encodings and colour models. It can decode eligible JPEG streams and certain eight-bit, deflate-compressed images. It skips tiny decorations and leaves colour models such as CMYK alone. For each candidate, it tries JPEG quality and dimension limits in order, starting at quality 0.82 with a longest side of 2,600 pixels. A trial that makes an individual image larger buys us nothing. This is the guard inside the replacement loop in src/workers/pdf-compress.worker.ts.

const e = chosen![i];
if (e.bytes.length >= c.oldLen) return;
Enter fullscreen mode Exit fullscreen mode

There’s a separate trade-off for tagged PDFs. If the document is still above target, the worker can remove its structure tree. A paragraph can remain selectable even after it loses information a screen reader uses for navigation. If I’m preparing an accessible publication, copying a sentence is only one check. I also check the reading order and headings in the resulting document and keep the tagged original.

When Extreme mode actually draws a page

Extreme mode returns the vector result immediately if it fits. When that pass misses the target, the UI opens a fresh copy of the original bytes with PDF.js. Going back to the original matters here. Rendering an image that Smart has already downsampled would spend another generation of JPEG loss before we had even chosen the final resolution.

The following three lines are from src/tools/CompressPdf.tsx. Here, vp is the viewport at scale one and RENDER_SCALE is 1.5.

const scale = Math.min(RENDER_SCALE, 2400 / Math.max(vp.width, vp.height));
const canvas = await renderPage(page, scale);
pages.push({ bitmap: await createImageBitmap(canvas), widthPt: vp.width, heightPt: vp.height });
Enter fullscreen mode Exit fullscreen mode

On an ordinary page, 1.5 times 72 PDF points per inch gives a nominal 108 DPI. The 2,400-pixel cap also bounds the longest edge of an unusually large page. The UI releases each HTML canvas after creating its bitmap and transfers the bitmaps to the worker. The worker uses OffscreenCanvas to try smaller dimensions and JPEG settings without asking PDF.js to draw the source document again.

At each resolution the worker tests the lowest quality in the tier. If that fits its byte estimate, it searches for a higher quality at the same resolution. Extreme can go as low as a nominal 36 DPI on an uncapped page, where a decimal point or the tail of a digit can disappear. Finally, pdf-lib creates pages at their original physical dimensions and draws one JPEG across each. A page built that way has no embedded text to select. If flattening produces a larger result than Smart, the UI keeps the vector version. The final size comparison can also return the original file.

A two-file benchmark

Use the 200 KB preset for both modes. Its budget is 204,800 bytes. Start each run with the original and measure the downloaded file in bytes. Use a scan without an OCR layer for one input and a document with a known selectable phrase for the other. For each output, try copying that phrase with automatic OCR disabled. A viewer that recognises text in pictures can otherwise hide what the compressor did.

I ran both modes through the exported app in Chrome 158.0.8127.37. The scan was a synthetic US Letter service record with twelve 1,000 × 1,300 JPEGs, one per page. The text fixture had 32 Letter pages with 40 lines of 11-point Helvetica per page. I reopened each downloaded Blob with PDF.js and checked whether page one had an extractable “Service record” phrase. That tests the embedded text layer independently of a viewer’s OCR.

Sample Original Size Smart Mode Size Text Selectable? Extreme Mode Size Text Selectable?
Raster scans, 12 pages 10,428,319 B 366,425 B No 190,995 B No
Text report, 32 pages 15,688 B 15,446 B Yes 15,446 B Yes

To recreate the fixtures, draw “Service record P / entry N” with one-based page and entry numbers. For the report, place lines at x = 40 and y = 750 − 18k points, starting with k = 0. For each scan, draw 32 lines in black 24 px Arial at (45, 65 + 36k) over grey noise. Seed the noise with the page number, advance once per pixel using (1664525 × seed + 1013904223) modulo 2³², and add 185 to the top six bits for each grey value. Embed the canvas as a JPEG at quality 0.96 across a 612 × 792 point page. Both fixtures used pdf-lib’s default save settings with metadata updates disabled. Browser JPEG encoders and installed fonts can affect the exact byte count.

The scan needed flattening to meet the limit and had no text layer to lose. The report fit on the first pass. Extreme returned the same selectable version because spending pixels on those 1,280 lines would serve no purpose.

Test it in Airplane Mode

Load the page while connected and run a disposable example that reaches the raster stage so the browser fetches the lazy-loaded PDF.js code and its worker. Keep the tab open, disconnect all network interfaces, then select a different local PDF, compress it and open the download. Starting with a fresh file after disconnecting is the important part of the test. The app reads the file into browser memory, processes it there and creates a downloadable Blob. There’s no backend upload endpoint in that path. For my support workflow, the last check is mundane but decisive. Can I still copy the part number that prompted me to share the document?

Built by **Asad Ali* — IT Support & Security Operations Engineer (Microsoft SC-200 & ISC2 CC Certified). Creator of OfflineFileLab.com and LocalSecTools.com — 100% client-side privacy and security workbenches where sensitive files and logs never leave your browser. Portfolio: asadali.tech*

Top comments (0)