How I Built a 100% Offline Word (.docx) vs PDF Contract Diff Tool in a Single HTML File
If a client emails you a redlined NDA or consulting contract as a PDF while your original draft is in Word (.docx), comparing them usually forces an uncomfortable choice: Upload confidential legal agreements to a free
If a client emails you a redlined NDA or consulting contract as a PDF while your original draft is in Word (.docx), comparing them usually forces an uncomfortable choice:
- Upload confidential legal agreements to a free online diff website (potentially violating NDA terms).
- Pay $15β$40/month (or $199+/year) for desktop diff software you only open a few times a month.
I wanted something radically simpler: a single, self-contained .html file that you can open directly in any browserβeven in airplane modeβdrop a .docx on the left and a .pdf on the right, and get a clean word-level diff with zero network calls.
You can try the live browser-local demo right now (it runs strictly in your browser with no backend):
Live 1-Click Offline Demo (GitHub Pages)
Here are the four most interesting engineering hurdles I ran into while building itβand the exact JavaScript patterns that solved them.
1. Parsing .docx in ~60 Lines of Zero-Dependency JavaScript
A .docx file is just a PKZIP archive containing word/document.xml. Most tutorials tell you to pull in jszip + mammoth, but modern browsers already ship with DecompressionStream("deflate-raw").
By scanning the ZIP End of Central Directory (EOCD) record (0x06054b50) from the end of the file, we can safely handle .docx files saved by Microsoft Word, Google Docs, and LibreOfficeβeven when they use Data Descriptors (where compressed size isn't written in the local file header):
async function inflateRawBytes(compressedBytes) {
const ds = new DecompressionStream("deflate-raw");
const writer = ds.writable.getWriter();
writer.write(compressedBytes);
writer.close();
const chunks = [];
const reader = ds.readable.getReader();
let total = 0;
while (true) {
const { done, value } = await reader.read();
if (done) break;
chunks.push(value);
total += value.length;
}
const out = new Uint8Array(total);
let offset = 0;
for (const c of chunks) {
out.set(c, offset);
offset += c.length;
}
return out;
}
The Hidden Word Bug: Tracked Deletions (<w:del>)
When someone edits a .docx with Track Changes enabled, deleted text often remains inside word/document.xml wrapped in <w:del>...</w:del>. If you naively extract all text nodes, deleted clauses silently ghost back into your diff!
Stripping <w:del> blocks before collecting <w:t> runs guarantees you only compare the live contract text:
export function parseDocxXmlToParagraphs(xmlText) {
const cleaned = String(xmlText || "").replace(/<w:del\b[^>]*>[\s\S]*?<\/w:del>/g, "");
const paragraphs = [];
const pRegex = /<w:p\b[^>]*>([\s\S]*?)<\/w:p>/g;
let pm;
while ((pm = pRegex.exec(cleaned)) !== null) {
const pBody = pm[1]
.replace(/<w:tab\b[^>]*\/>/g, " ")
.replace(/<w:br\b[^>]*\/>/g, "\n");
const tRegex = /<w:t\b[^>]*>([\s\S]*?)<\/w:t>/g;
let text = "";
let tm;
while ((tm = tRegex.exec(pBody)) !== null) {
text += decodeXmlEntities(tm[1]);
}
for (const ln of text.split("\n").map((s) => s.trim()).filter(Boolean)) {
paragraphs.push(ln);
}
}
return paragraphs;
}
2. Fixing the Classic PDF.js English Word-Gluing Bug
When you extract text from a PDF via page.getTextContent() in Mozilla PDF.js, many PDF generators split words via X-coordinate positioning instead of literal " " space characters.
If you simply concatenate items on the same baseline (last.text += it.str), "Consulting Agreement" turns into "ConsultingAgreement"βcausing massive false positives when comparing against .docx.
The fix is to compute each glyph run's visual font size and compare the horizontal gap it.x - last.endX against a fraction of the font size (0.18 * fontSize):
const gap = it.x - last.endX;
const needsSpace =
gap > it.fontSize * 0.18 &&
!/\s$/.test(last.text) &&
!/^\s/.test(it.str);
last.text += (needsSpace ? " " : "") + it.str;
last.endX = Math.max(last.endX, it.x + it.width);
That tiny geometric check eliminated almost all false word-merge diffs across real-world PDFs exported from Word, Google Docs, and DocuSign.
3. Absorbing Word β PDF Typography Noise (Ligatures & Smart Quotes)
Even after clean extraction, comparing .docx against .pdf produces noisy diffs because PDF exporters often convert "fi" / "fl" into Unicode ligatures (\uFB01, \uFB02), swap straight quotes for curly quotes (β β), or emit non-breaking spaces (\u00A0).
Running a lightweight normalization layer before LCS comparison keeps the redline focused on real business changesβlike $5,000 Net 15 quietly changing to $4,500 Net 45, or IP ownership shifting from "upon full payment" to "upon creation":
export function normalizeForComparisonEn(text, options = {}) {
let s = String(text || "");
if (options.ignoreTypographyAndSpace !== false) {
s = s
.replace(/\uFB00/g, "ff")
.replace(/\uFB01/g, "fi")
.replace(/\uFB02/g, "fl")
.replace(/\uFB03/g, "ffi")
.replace(/\uFB04/g, "ffl")
.replace(/[\u2018\u2019\u201A]/g, "'")
.replace(/[\u201C\u201D\u201E]/g, '"')
.replace(/[\u2013\u2014\u2212\u2010]/g, "-")
.replace(/\u00A0/g, " ")
.replace(/\s+/g, " ")
.trim();
}
if (options.ignoreCase === true) s = s.toLowerCase();
return s;
}
4. Proving "Zero Cloud Uploads" Technically (CSP + Blob Worker)
Saying "we respect your privacy" on a marketing page means nothing if an app still loads external scripts or analytics.
Instead, I compiled pdf.min.js inline, embedded pdf.worker.min.js as a Base64-decoded Blob URL, and locked the entire document with a strict <meta> Content Security Policy:
<meta
http-equiv="Content-Security-Policy"
content="default-src 'none'; script-src 'unsafe-inline' blob:; worker-src blob:; style-src 'unsafe-inline'; img-src data:; connect-src 'none'; base-uri 'none'; form-action 'none';"
>
Because connect-src 'none' is enforced by the browser engine itself, even if you inspect DevTools β Network while dropping confidential .docx and .pdf files, zero outbound requests can occurβand the file runs identically under file:// with Wi-Fi turned off.
Try It Yourself (No Signup Needed)
-
Free 1-Click Live Demo (up to 40 paragraphs): https://mscsupport2026-lab.github.io/difflocal-demo/
- Click "Load Sample Contract" to immediately see silent clause edits highlighted, or drag & drop your own
.docx/ text-layer.pdffiles.
- Click "Load Sample Contract" to immediately see silent clause edits highlighted, or drag & drop your own
- GitHub Demo Repo: https://github.com/mscsupport2026-lab/difflocal-demo
(Full disclosure: The free demo compares the first 40 paragraphs right in your browser. If you need unlimited contract length, 1-click Printable Audit HTML Reports, Excel/Sheets Review Checklist CSV exports, and the downloadable standalone offline .html file, I also offer **DiffLocal Pro* as a one-time $39 purchase on Gumroad. Note: This tool uses Mozilla PDF.js under Apache 2.0 and does not support scanned image-only PDFs without OCR text. Parts of the drafting and test scaffolding were assisted by AI tools and verified with automated tests.)*
If you have thoughts on handling multi-column PDF layouts or table-cell diffs cleanly in pure JS, I'd love to hear your approach in the comments!
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.