Build an Offline PDF Toolkit with pdf-lib and pdf.js

Краткое содержание

Pixel’s announcement explores building a PDF toolbox that processes files entirely in the browser without uploading them. It details how pdf-lib handles editing and pdf.js renders previews, with both libraries bundled locally and a blob-based worker enabling offline use.

DEV Community

How I built offline PDF processing with pdf-lib and pdf.js in the browser

Every "free online PDF tool" does the same thing: you drag a file into the page, and that file is uploaded to a server you'll never see, in a region you can't name, for a retention period nobody specifies. I wanted a PDF toolbox that never uploads anything. Not "we delete it after an hour" — never sends it at all. That meant all parsing, modification and serialization had to happen inside the browser tab. This is what that architecture looks like, and where it gets painful. The constraint that shapes everything Once you decide the file can't leave the device, a few things become impossible: No server-side Ghostscript for compression No server-side qpdf for encryption No "process in the background and email you the result" No file size limit that only exists because of your server's disk Everything has to run in a single tab, with the memory a mobile browser is willing to give you. That constraint dictates the entire library choice. Two libraries, two very different jobs The split that ended up working: pdf-lib — writing. Merge, split, rotate, delete pages, watermark, encrypt. It gives you a mutable document model and serializes it back to bytes. pdf.js — reading. Rendering thumbnails and page previews so users can pick pages before operating on them. Both are vendored and inlined into the HTML. No CDN, no dynamic import. The page works from a cold cache with the network off. Getting pdf.js to run without a bundler pdf.js needs its worker. The usual failure is a cross-origin worker URL, which browsers refuse to construct: // fails in most browsers when the script is served from another origin
pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdn.example.com/pdf.worker.min.js';
The fix that works everywhere, including file://-ish and offline scenarios, is to build the worker from a blob: const blob = new Blob([pdfjsWorkerSource], { type: 'application/javascript' });
pdfjsLib.GlobalWorkerOptions.workerSrc = URL.createObjectURL(blob);
pdfjsWorkerSource is the worker bundle as a string, inlined at build time. Costs you about 1MB of HTML, buys you zero network requests and no CORS surprises. Merge, split, rotate: the easy 10% pdf-lib's document model is genuinely pleasant here. Merging is copy-pages: async function mergePdfs(files) {
const out = await PDFLib.PDFDocument.create();

for (const file of files) {
const bytes = await file.arrayBuffer();
const src = await PDFLib.PDFDocument.load(bytes);
const pages = await out.copyPages(src, src.getPageIndices());
pages.forEach(p => out.addPage(p));
}

return out.save(); // Uint8Array
}
Split and rotate are variations on the same theme. If your tool only did these, you could ship in an afternoon. The interesting problems are compression and encryption. Compression: pdf-lib does less than you think Here's the part that surprises people. pdf-lib cannot re-encode embedded images. It has no JPEG/JPEG2000 decode pipeline, no downsampler. When you call save(), it applies FlateDecode to content streams and leaves image streams alone. So "compress PDF in the browser" really means: strip redundancy from the streams you can touch, and accept that a scan-heavy PDF won't shrink much. The implementation that actually produced useful results was to re-deflate streams myself with pako at a chosen level: // pdf-lib's internal pako defaults to roughly level 6.
// Re-deflating lets us expose a real Low/Medium/High choice.
function reCompressStreams(pdfBytes, level) {
const doc = PDFLib.PDFDocument.load(pdfBytes, { updateMetadata: false });
// for each content stream: inflate -> deflate at level
// (pdf-lib exposes the parsed objects; raw stream re-encode is done manually)
}
Two honest caveats I had to surface in the UI: Low compression can make the file bigger. If the original was deflated at level 9, re-deflating at level 1 grows it. That's not a bug, and pretending otherwise produces angry users. Image-heavy PDFs barely move. A 20MB scanned document is 19MB of JPEG....
Build an Offline PDF Toolkit with pdf-lib and pdf.js
Powered by Readybot.io

Последнее от Pixel

Incident Response: Look Beyond the Red Alert

Pixel’s DEV Community announcement explores how teams can fixate on one failing service while overlooking the real cause of an outage, such as a full …

Sach: AI Fact-Checks WhatsApp Forwards in India

Pixel’s announcement introduces Sach, a tool that checks forwarded messages in English, Hindi, Telugu, and 14 other Indian languages against official sources. It gives cited …

Java 25 Removes SecurityManager: What to Fix

Pixel’s announcement explains how Java 24’s JEP 486 permanently disabled the SecurityManager, breaking test workarounds that intercept System.exit. It recommends returning exit codes or throwing …

Why a Java HPA Got Stuck at 20 Kubernetes Pods

Pixel shares how a Spring Boot pricing service autoscaled to 20 Kubernetes pods and stayed there because the JVM retained committed heap memory after traffic …