DEV Community

Apps66
Apps66

Posted on Originally published at apps66.com

Browser-Local PDF Visual Diff with PDF.js: Streaming Page-by-Page Diffs in ~7 MB RAM

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.

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:

  1. 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.
  2. Visual and layout drift: A shifted signature line, clipped table cell, rotated stamp, or swapped brand logo never appears in a text-only comparison.
  3. Reading-order artifacts: Multi-column invoices and financial tables often extract text in unpredictable stream order, creating false positives when only one number changed.
  4. 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:

  1. Render page i of PDF A onto a canvas, then immediately call page.cleanup() so PDF.js frees decoded font and image caches for that page.
  2. Render page i of PDF B onto its canvas and call page.cleanup().
  3. 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.
  4. Release the raw Uint8ClampedArray buffers 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 pass isEvalSupported: false to getDocument().
  • Bundle the official legacy build under .js extensions: Modern pdfjs-dist bundles use ES2025 APIs such as Uint8Array.prototype.toHex() that break Chromium < 140 and older Safari, while stock Nginx often serves .mjs as application/octet-stream. Serving the official legacy/build files with .js extensions guarantees native application/javascript MIME 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 });
}
Enter fullscreen mode Exit fullscreen mode

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

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.

Top comments (1)

Collapse
 
burthcer profile image
Dev Bhamaria •

The 350 MB versus 7 MB comparison makes the case clearly: holding both documents in memory before comparing is what kills phones. I build PDF tools that also run locally, and page-at-a-time is the part I find hardest to keep honest. When the two revisions have different page counts or an inserted page, how do you decide which pages to pair up?