Compressing PDFs in the browser, and the bug that shipped empty files
dev.to·
Working with browser-side binary manipulation can introduce subtle bugs if memory state and array buffer lifecycles aren't managed carefully. This write-up details a production issue encountered while implementing PDF compression in the browser using `pdf-lib` and `pdfjsLib`. When compressing a file yielded no size reduction, the fallback logic returned the original file buffer wrapped in a Blob. However, handing the `ArrayBuffer` directly to `pdfjsLib.getDocument` mutated or detached the underlying buffer, causing the fallback path to ship empty files to users. The solution requires explicit cloning using `buf.slice(0)` before passing memory buffers to third-party libraries. Understanding these low-level JavaScript memory dynamics is essential for senior developers building reliable web clients that process files in-browser.