Merge and compress PDFs in the browser with pdf-lib and PDF.js (no server, no upload)
Most "free PDF tools" upload your file to a server, process it, and send it back. For a contract, a bank statement or a scanned ID, that is a real privacy cost, and it isn't necessary. Modern browsers can do most everyday PDF jobs locally. In this post I'll show the two operations people ask for most, merge and compress , using two libraries: pdf-lib to create and modify PDF documents. PDF.js…
Both PDF-lib and PDF.js enable merging and compressing PDFs directly in a user's web browser, eliminating the need for server-side processing or file uploads. This approach preserves user privacy and avoids potential security risks associated with transmitting sensitive documents to external servers.
Merging PDFs is a straightforward task using pdf-lib. The process involves loading each input file, copying its pages into a new PDF document, and saving the combined output. The function mergePdfs accepts an array of file objects, loads each file, and appends its pages to the output document. The resulting merged PDF is then saved using object streams to optimize its size.
Compressing a PDF primarily focuses on image content, as vector graphics and text are inherently compact. pdf-lib provides the useObjectStreams flag to enable object stream compression, which reduces the file size by about 5-15% for text-heavy PDFs. However, this method cannot re-encode embedded images. To achieve significant compression of scanned documents, rasterization is required.
This involves rendering each page to a canvas, encoding it as a JPEG with a reduced quality setting, and creating a new PDF containing these compressed images. This approach is lossy, meaning some image quality is sacrificed, but it can result in substantial file size reductions.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.