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

A commenter told me where my PDF compressor was wasting memory. They were right.

A few weeks ago I wrote here about PDFRoll, a set of PDF tools that run entirely in the browser. In that post I admitted the weak spot: when there is no server, the memory limit is the visitor's device, and a long scan o

A few weeks ago I wrote here about PDFRoll, a set of PDF tools that run entirely in the browser. In that post I admitted the weak spot: when there is no server, the memory limit is the visitor's device, and a long scan on an old phone can run out of it.

Someone from KomoPDF, who builds the same kind of tool, left a comment with four suggestions: call page.cleanup(), move rendering to a worker with OffscreenCanvas, cap the render scale, and downsample images instead of rasterizing whole pages.

I said I would fix the first ones first. This is what I changed, what I measured, and what I haven't done yet.

How the compressor works

The "strong" compression mode renders every page to a canvas with PDF.js, encodes the canvas as a JPEG, and builds a new PDF from those images with pdf-lib. One page at a time, in a loop.

The loop looked fine. It was sequential, so I assumed only one page was ever in memory. That assumption was wrong in more places than I expected.

Problem 1: the canvas outlived the page

Here is roughly what the loop did:

const { canvas, size } = await renderPage(pdf, i, scale);
const img = await out.embedJpg(await (await canvasToBlob(canvas, 'image/jpeg', quality)).arrayBuffer());
out.addPage([size.width, size.height]).drawImage(img, { /* ... */ });

The canvas is a local variable, so it gets garbage collected eventually. "Eventually" is the problem. A canvas holds its pixel buffer outside the JavaScript heap, and the browser has no reason to rush. On a page rendered at 2x, that's around 2 million pixels × 4 bytes, so about 8 MB that can stay alive while the next page is already rendering.

The fix is boring. Set the canvas size to zero as soon as you have the JPEG bytes. That releases the buffer right away instead of whenever the GC gets around to it:

function releasePage({ canvas, page }) {
  canvas.width = canvas.height = 0;
  try { page.cleanup(); } catch { /* already released */ }
}

The order matters too. I now release the canvas before pdf-lib embeds the JPEG, so the raw pixels and the encoded image never sit in memory together:

const r = await renderPage(pdf, i, scale, { maxPixels: MAX_RENDER_PIXELS });
const jpg = await (await canvasToBlob(r.canvas, 'image/jpeg', quality)).arrayBuffer();
releasePage(r);  // before embedding: one canvas alive at a time
const img = await out.embedJpg(jpg);

Problem 2: PDF.js kept every page's resources

This is the one from the comment. When PDF.js renders a page, it decodes fonts and images and keeps them on the page object in case you render it again. I never render a page twice, so for a 60-page scan that's 60 pages of decoded images kept for nothing.

page.cleanup() drops them. My PDF-to-JPG tool already called it. The compressor didn't, because I wrote the two at different times and only fixed one. That's the honest explanation for most bugs I find.

Problem 3: documents nobody closed

The compressor computes all three compression levels as soon as you pick a file, so it can show the resulting size next to each option. Each level opens the PDF with PDF.js. None of them ever closed it.

There was a fourth one I hadn't noticed: a quick call that opens the file just to count its pages. It read numPages and walked away, leaving a whole parsed document in memory for the rest of the session.

Now every document is closed in a finally, and the page counter closes its document immediately:

const doc = await openWithPdfJs(file).catch(() => null);
const pages = doc?.numPages || 0;
doc?.destroy();  // we only needed the page count

Problem 4: no ceiling on page size

The render scale was fixed per compression level, and I had only thought about letter and A4 pages. Then I tried an A0 poster. At scale 2 that's a canvas of roughly 32 million pixels, about 128 MB for a single page. On a phone, that alone can be enough to crash the tab.

So the render is now capped at 16 million pixels per page. If a page would go over, the scale is reduced just enough to fit:

const MAX_RENDER_PIXELS = 16e6;

if (maxPixels) {
  const base = page.getViewport({ scale: 1 });
  const px = base.width * base.height * scale * scale;
  if (px > maxPixels) scale *= Math.sqrt(maxPixels / px);
}

16 Mpx is about 4000 × 4000. A normal page never gets close, so nothing changes for 99% of files. A poster gets slightly lower resolution instead of a crash.

What I measured

I tested in Chromium with a script that records the largest canvas the compressor creates:

  • A0 poster with a large photo: biggest canvas went from about 32 Mpx to 16 Mpx. The file went from 2 MB to 1.2 MB.
  • 12-page scan, compressed to an 800 KB target: 1.3 MB down to 573 KB, all pages processed, no errors.
  • Text PDFs: unchanged results, because the tool still keeps the lossless version when it's within 15% of the raster one.

What I haven't measured yet is peak memory on a real low-end phone. I've seen enough guessed numbers in blog posts to not add my own. If you have an old Android and a long scanned PDF, I'd love to know if it survives now.

What I didn't do (yet)

The other two suggestions from the comment are still on my list:

  • Rendering in a worker with OffscreenCanvas. It would stop the page from freezing during long jobs. It's a bigger change, because PDF.js setup and the progress messages both have to move.
  • Downsampling embedded images instead of rasterizing pages. That's the real fix for scans: keep the text layer and only shrink the images. It means rewriting image streams with pdf-lib, which is where I expect most of the bugs to be.

The part I want to remember

None of these were clever bugs. They were small things that a desktop with 16 GB of RAM forgives and a phone doesn't. I had tested on my own machine and decided it was fine.

A stranger read my post and pointed straight at what I'd missed for weeks. Writing in public about the weak spot was the most useful thing I did for this tool.

If you've shipped heavy canvas work in the browser, I'm still curious: did moving to a worker actually reduce crashes for you, or only the freezing?

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