Comparing two PDF revisions sounds simple until you check a real contract redline, packaging print proof, or quarterly financial filing. Plain text diff tools miss shifted logos, substituted fonts, altered barcode margins, and embedded table edits, while most online PDF comparators require uploading confidential NDAs and pre-press files to a remote server.
This engineering guide walks through how to run a 100% browser-local PDF visual diff using self-hosted PDF.js: keeping peak raw pixel RAM near ~7 MB even on 50-page documents, defending against malicious third-party PDF fonts (CVE-2024-4367), clustering pixel diffs into clean bounding-box regions, and generating XSS-safe HTML/CSV review reports.
- Try the live browser-local tool (zero uploads): Apps66 Compare PDF Visual Diff
- Standalone zero-dependency MIT diff core: PeakProductivity/pdf-pixel-diff-core
- Original canonical engineering guide: Apps66 Engineering Blog
Why Text-Only PDF Diffs Miss Critical Revisions
Extracting raw text from two PDFs works for simple prose, but it breaks down across real commercial documents in four ways:
- Outlined fonts and scans: Print shops routinely outline typography before press. Text extractors return an empty string even when a headline or price changed completely.
- Visual and layout drift: A shifted signature line, clipped table cell, rotated stamp, or swapped brand logo never appears in a text-only comparison.
- Reading-order artifacts: Multi-column invoices and financial tables often extract text in unpredictable stream order, creating false positives when only one number changed.
- Confidentiality risk on remote servers: Legal, compliance, and print teams cannot upload unreleased agreements to cloud servers just to verify revisions.
Streaming Page-by-Page Architecture: ~7 MB vs 350 MB RAM
The fastest way to crash mobile Safari or Chrome when building a browser-local PDF comparator is a naive two-phase loop: render all 50 pages of PDF A into RGBA buffers, render all 50 pages of PDF B into RGBA buffers, and only then compare page 1 through page 50.
At a crisp proofing scale (~1.35x, roughly 826 x 1069 px for US Letter), each uncompressed RGBA ImageData buffer takes ~3.5 MB. Holding 50 pages from both files simultaneously pins over 350 MB of raw pixel buffers before counting canvases or previews.
Instead, open both documents concurrently and process strictly one page pair at a time:
- Render page
iof PDF A onto a canvas, then immediately callpage.cleanup()so PDF.js frees decoded font and image caches for that page. - Render page
iof PDF B onto its canvas and callpage.cleanup(). - Normalize both frames to matching dimensions on a white backdrop, run
compareRgba(), encode compact WebP previews for Original, Revised, and Diff Overlay, and zero canvas dimensions (canvas.width = 0; canvas.height = 0;) so GPU backing stores free immediately. - Release the raw
Uint8ClampedArraybuffers at the end of every loop iteration so peak live pixel RAM stays bounded around ~7 MB whether the document has 4 pages or 50 pages.
Hardening PDF.js for Untrusted Third-Party PDFs
Three production hardening steps matter when users drop third-party vendor or client PDFs into a browser-local workbench:
- Disable dynamic font JS evaluation (
isEvalSupported: false): Older PDF.js versions suffered from CVE-2024-4367, allowing crafted PDF fonts to execute attacker-controlled JavaScript in your origin. Ship a current PDF.js release AND explicitly passisEvalSupported: falsetogetDocument(). - Bundle the official
legacybuild under.jsextensions: Modernpdfjs-distbundles use ES2025 APIs such asUint8Array.prototype.toHex()that break Chromium < 140 and older Safari, while stock Nginx often serves.mjsasapplication/octet-stream. Serving the officiallegacy/buildfiles with.jsextensions guarantees nativeapplication/javascriptMIME headers and broad browser support. - Mask document previews from analytics: Wrap the comparator container in privacy-mask attributes (
data-clarity-mask="true",fs-exclude) so third-party UX telemetry can never capture contract previews or filenames.
// Hardened streaming page-by-page PDF.js diff loop (MIT core: PeakProductivity/pdf-pixel-diff-core) import { compareRgba, classifyPageStatus } from './pdf-pixel-diff-core.js'; const leftTask = pdfjs.getDocument({ data: leftBytes, isEvalSupported: false }); const rightTask = pdfjs.getDocument({ data: rightBytes, isEvalSupported: false }); const [leftDoc, rightDoc] = await Promise.all([leftTask.promise, rightTask.promise]); for (let p = 1; p <= Math.max(leftDoc.numPages, rightDoc.numPages); p++) { const left = p <= leftDoc.numPages ? await renderAndCleanup(leftDoc, p) : null; const right = p <= rightDoc.numPages ? await renderAndCleanup(rightDoc, p) : null; const norm = normalizePairAndReleaseCanvases(left, right); const diff = compareRgba(norm.left.data, norm.right.data, norm.width, norm.height, 24); const status = classifyPageStatus(Boolean(left), Boolean(right), diff.changedPixels); results.push({ pageNumber: p, status, regions: diff.regions, differencePercent: diff.differencePercent }); } Tuning Sensitivity Thresholds and Clustering Change Regions
| Sensitivity Mode | Channel Threshold | What It Filters | Best Document Types |
|---|---|---|---|
| Strict | 8 | Tiny 1-bit rounding jitter only | Press artwork, packaging dielines, CMYK proofs |
| Standard (Default) | 24 | Subpixel font anti-aliasing and smoothing | Contracts, legal redlines, invoices, financial reports |
| Relaxed | 48 | Light scanner brightness drift and JPEG grain | Scanned agreements, photocopied or faxed forms |
Grouping changed pixels on a 16x16 grid with 4-way connected-component BFS turns thousands of individual changed pixels into a handful of crisp bounding boxes, letting reviewers jump straight to every modified clause or graphic.
XSS-Safe Visual HTML and CSV Review Reports
When generating downloadable sign-off reports purely client-side:
- Escape every filename and metadata string before interpolating into standalone HTML.
- Allowlist only strict base64 image URIs (
^data:image/(png|webp|jpeg);base64,[A-Za-z0-9+/=]+$). - Keep CSV ledgers strictly numeric and enum-bound (
page,status,difference_percent,changed_pixels,regions) to prevent spreadsheet formula injection.
Complete Browser-Local Pre-Press and Document Stack
- Strip vendor print/copy locks first if needed with Unlock PDF.
- Visually inspect revisions locally with Compare PDF Visual Diff, then assemble or trim final packets with Merge PDF and Extract PDF Pages.
- Working on vector artwork or e-commerce catalog feeds? Vectorize logos locally via VTracer WASM at PNG to SVG Vectorizer or audit Seller Central spreadsheets locally with Amazon Flat File Checker.
Test the full streaming PDF.js comparator with the built-in 4-Page Demo Pair at apps66.com/compare-pdf, or grab the MIT diff core on GitHub at PeakProductivity/pdf-pixel-diff-core.

