Dev.to WebDev 🛠 Dev 👁 0 📖 4 min read

Why Black Overlay Rectangles Fail in PDF Redaction — Building Irreversible Client-Side Masking in TypeScript

If you have ever seen a "redacted" PDF where someone drew a black rectangle over an Aadhaar number, Social Security Number, or bank account detail in a basic viewer, there is a good chance you can still copy and paste th

If you have ever seen a "redacted" PDF where someone drew a black rectangle over an Aadhaar number, Social Security Number, or bank account detail in a basic viewer, there is a good chance you can still copy and paste the hidden text right out of the document.

In PDFs, visual appearance and underlying data live in separate constructs. Understanding why naive overlay redaction fails—and how to replace it with an irreversible, zero-upload browser pipeline—is essential if you build document workflows in TypeScript.

Why Black Vector Overlays Leak Data

A PDF page is not a flat image. Its visual instructions live in a content stream composed of low-level operators:

  • BT / ET delimit text objects
  • Tf selects a font and size
  • Tm / Td position the text matrix
  • Tj and TJ render character strings and glyph positioning arrays
  • re and f define and fill vector rectangles

When a naive tool draws a black box over sensitive text, it simply appends a vector fill command (such as 0 0 0 rg ... re f) or attaches a PDF annotation on top of the existing content stream. Nothing removes the original Tj or TJ operators underneath.

Because those text operators remain intact in the page stream, anyone with a PDF parser can extract the "redacted" string in seconds using pdfjs-dist:

import * as pdfjsLib from 'pdfjs-dist';

export async function extractAllText(pdfBytes: Uint8Array): Promise<string> {
  const loadingTask = pdfjsLib.getDocument({ data: pdfBytes });
  const pdf = await loadingTask.promise;
  const chunks: string[] = [];

  for (let pageNum = 1; pageNum <= pdf.numPages; pageNum++) {
    const page = await pdf.getPage(pageNum);
    const content = await page.getTextContent();
    const pageText = content.items
      .map((item) => ('str' in item ? item.str : ''))
      .join(' ');
    chunks.push(pageText);
  }

  return chunks.join('\n');
}

Even worse, PDFs frequently carry leaks outside the visible content stream: /Info dictionary fields, XMP /Metadata XML blocks, interactive /AcroForm fields, annotations, and incremental %%EOF revision history can all retain unredacted data if you mutate an existing document in place.

Irreversible Client-Side Masking in the Browser

To make redaction genuinely irreversible and avoid sending sensitive identity documents to third-party servers, we can run the entire pipeline locally inside the user's browser:

  1. Zero Server Exposure: Government IDs, tax filings, and financial statements never leave the device. No upload endpoints, no temporary cloud buckets, and no server logs.
  2. Rasterization + Pixel Burn-In (pdfjs-dist + HTML5 Canvas): Render each PDF page onto an HTML5 <canvas> at a crisp scale (for example, 2.0x for sharp typography), then paint solid opaque rectangles directly onto the 2D pixel buffer over the user-selected coordinates:
// Render PDF page via pdfjs-dist into a 2D canvas context
await page.render({ canvasContext: ctx, viewport }).promise;

// Burn solid mask regions directly into the rasterized pixels
ctx.fillStyle = '#000000';
for (const box of redactionBoxes) {
  ctx.fillRect(box.x, box.y, box.width, box.height);
}

const flattenedPng = await new Promise<Blob>((resolve, reject) => {
  canvas.toBlob(
    (blob) => (blob ? resolve(blob) : reject(new Error('Canvas export failed'))),
    'image/png'
  );
});

Once exported as a flattened bitmap, the original Tj/TJ glyph operators are gone. Those coordinates contain only black pixels—there is no hidden text layer left to select or parse.

  1. Clean Document Rebuild & Metadata Scrubbing (@cantoo/pdf-lib): Instead of modifying the source PDF in place (which risks leaving behind old XMP streams or trailer objects), create a brand-new PDFDocument with @cantoo/pdf-lib, embed the flattened page images, and explicitly scrub document metadata:
import { PDFDocument } from '@cantoo/pdf-lib';

export async function rebuildCleanPdf(pagePngs: ArrayBuffer[]): Promise<Uint8Array> {
  const cleanDoc = await PDFDocument.create();

  for (const pngBytes of pagePngs) {
    const image = await cleanDoc.embedPng(pngBytes);
    const page = cleanDoc.addPage([image.width, image.height]);
    page.drawImage(image, {
      x: 0,
      y: 0,
      width: image.width,
      height: image.height,
    });
  }

  // Scrub all standard metadata fields
  cleanDoc.setTitle('');
  cleanDoc.setAuthor('');
  cleanDoc.setSubject('');
  cleanDoc.setKeywords([]);
  cleanDoc.setCreator('');
  cleanDoc.setProducer('');

  return cleanDoc.save({ useObjectStreams: false });
}

Because we build a fresh PDF structure from rasterized images, old incremental updates, annotations, form values, and hidden metadata trailers are completely eliminated.

Automated Verification with Vitest

Visual inspection is never enough for security-critical redaction. Every masking pipeline should have automated tests verifying that sensitive patterns—such as SSNs, Aadhaar numbers, or bank account numbers—cannot be recovered from either pdfjs-dist text extraction or raw byte streams.

In Vitest, you can test against synthetic fixture PDFs and assert zero leakage after masking:

import { describe, it, expect } from 'vitest';
import { extractAllText } from './extractText';
import { maskPdfRegions } from './maskPdf';

describe('Irreversible PDF Redaction', () => {
  it('removes SSN, Aadhaar, and bank account strings from extracted streams and raw bytes', async () => {
    const fixtureBytes = await buildSyntheticPdfWithText([
      'SSN: 123-45-6789',
      'Aadhaar: 1234 5678 9012',
      'Account: 987654321098',
    ]);

    const redactedBytes = await maskPdfRegions(fixtureBytes, redactionBoxes);

    // 1. Verify pdfjs-dist finds zero recoverable text operators
    const extracted = await extractAllText(redactedBytes);
    expect(extracted).not.toMatch(/123-45-6789/);
    expect(extracted).not.toMatch(/1234\s?5678\s?9012/);
    expect(extracted).not.toMatch(/987654321098/);

    // 2. Verify raw PDF bytes/trailers do not leak plaintext strings
    const rawAscii = new TextDecoder('latin1').decode(redactedBytes);
    expect(rawAscii).not.toContain('123-45-6789');
    expect(rawAscii).not.toContain('9012');
    expect(rawAscii).not.toContain('987654321098');
  });
});

Running these assertions on every build catches regressions immediately—for example, if a future refactor accidentally draws an annotation layer instead of burning pixels onto the canvas, or copies source metadata into the output document.

Wrapping Up

If you want to inspect the full implementation or run the test suite yourself, the source code is available in the open-source repository at github.com/Vishnu-cod/pdf-craft. If you ever need to quickly redact an ID document locally in your browser without uploading it anywhere, you can also try the client-side masker directly at pdf-craft-vert.vercel.app/mask-aadhaar.

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.