Dev.to Security πŸ” Cybersecurity πŸ‘ 0 πŸ“– 4 min read

How to Flatten a PDF and Remove Hidden Metadata Without Uploading Confidential Files

Every week, people fill out a W-9, sign a vendor onboarding packet, or annotate a contract, hit Save, and email the PDF assuming the document is locked. Two hours later, a client opens it in Apple Preview and sees blank

Every week, people fill out a W-9, sign a vendor onboarding packet, or annotate a contract, hit Save, and email the PDF assuming the document is locked. Two hours later, a client opens it in Apple Preview and sees blank form boxes, or worse, someone clicks into a field and alters a dollar figure or extracts the author's laptop username and edit history straight from the file bytes.

Knowing how to flatten a PDF properly, and when vector AcroForm flattening is not enough, requires looking at what actually lives inside a PDF file.

Why "Save" Leaves Your PDF Editable and Leaky

A filled PDF is rarely a static page. Behind the scenes, three separate structures often stay active after you click Save:

  1. Interactive /AcroForm and /Widget annotations: Text inputs, checkboxes, dropdowns, and radio buttons live in an interactive annotation layer floating on top of the static page stream. Different viewers (Apple Preview, Chrome PDFium, Adobe Acrobat Reader, court e-filing portals) render unflattened /Widget appearances inconsistently, and anyone opening the file can modify the values.
  2. Embedded /Info dictionary and catalog XMP /Metadata XML: Office suites and PDF readers write /Author, /Creator, /Producer, /Title, /Subject, /Keywords, /CreationDate, and /ModDate into both the classic trailer /Info dictionary and a separate root catalog XMP XML packet. Deleting /Author in a basic document properties panel frequently leaves the duplicate XMP XML stream intact.
  3. Incremental %%EOF save history: When a PDF editor performs an incremental save, it appends changes after the prior %%EOF marker rather than rebuilding the file from scratch. A PDF with 2 or more %%EOF trailers can still preserve earlier field values, previous metadata, and pre-redaction objects inside the raw file bytes.

Vector Flatten vs. Full-Page 200 DPI Image Flatten

Most guides lump both flattening techniques together, even though they solve different engineering problems:

Method What changes Text selectable? Best use case
Vector AcroForm Flatten Calls form.flatten() to burn /Widget appearances into static page drawing commands and strips /AcroForm + leftover annotations Yes (crisp vector text, small file) Filled W-9s, HR forms, rental agreements, tax packets
Full-Page 200 DPI Image Flatten Pre-flattens form appearances, rasterizes each page at 200 DPI, and rebuilds a clean single-revision PDF with zero editable layers No (pure flat image per page) Signed contracts, marked-up reviews, court e-filing, maximum lock

Why "Print to PDF" Often Breaks Forms

The classic workaround, printing to Microsoft Print to PDF or macOS Save as PDF, introduces silent defects:

  • Page boxes get rescaled to fit printer margins, clipping wide tables or shrinking legal-size pages.
  • Uncommitted AcroForm widgets and checkbox checkmarks can disappear in macOS Preview or Adobe Reader DC (which disables Print to PDF altogether on macOS).
  • The OS print spooler stamps fresh metadata (/Producer: macOS Quartz PDFContext or Microsoft: Print To PDF) right back into the output file.

Building a 100% Browser-Local PDF Flattener and Metadata Scrubber

You do not need a cloud upload server or a $240/yr desktop suite to inspect, flatten, and sanitize PDFs. Modern browsers can run the entire pipeline locally using pdf-lib and pdf.js with zero bytes leaving the user's device.

Step 1: Inspect Interactive Fields, Metadata, and %%EOF Revisions Locally

Before mutating anything, scan the local Uint8Array to count real risks:

import { PDFDocument, PDFName } from 'pdf-lib';

export function countPdfRevisions(bytes: Uint8Array): number {
  const latin1 = new TextDecoder('latin1').decode(bytes);
  const matches = latin1.match(/%%EOF/g);
  return matches ? matches.length : 1;
}

export async function inspectPdf(bytes: Uint8Array) {
  const doc = await PDFDocument.load(bytes, {
    ignoreEncryption: true,
    updateMetadata: false,
  });
  const form = doc.getForm();
  const fieldCount = form.getFields().length;
  const hasXmp = Boolean(doc.catalog.lookup(PDFName.of('Metadata')));
  const revisions = countPdfRevisions(bytes);
  return { fieldCount, hasXmp, revisions };
}

Step 2: Scrub Both /Info AND Catalog XMP /Metadata

Clearing doc.setAuthor('') alone leaves the catalog XMP XML stream behind. You must remove both:

export function scrubAllMetadata(doc: PDFDocument): void {
  doc.setTitle('');
  doc.setAuthor('');
  doc.setSubject('');
  doc.setKeywords([]);
  doc.setProducer('');
  doc.setCreator('');

  // Clear trailer /Info dictionary entries completely
  const infoRef = doc.context.trailerInfo.Info;
  if (infoRef) {
    doc.context.delete(infoRef);
    delete doc.context.trailerInfo.Info;
  }

  // Delete the root catalog XMP /Metadata stream
  const xmpRef = doc.catalog.get(PDFName.of('Metadata'));
  if (xmpRef) {
    doc.catalog.delete(PDFName.of('Metadata'));
    doc.context.delete(xmpRef);
  }
}

Step 3: One Subtle Gotcha with 200 DPI Raster Flattening

If you render an interactive AcroForm PDF straight through pdf.js onto an HTML <canvas> using annotationMode: 2 (ENABLE_FORMS), form widget text is rendered into a separate DOM overlay layer rather than painted directly onto the 2D canvas. Your flattened image will come out with empty boxes!

The reliable fix is a two-stage local pass:

  1. Run pdf-lib form.flatten({ updateFieldAppearances: true }) first so every text value, dropdown selection, and checkbox checkmark becomes part of the page's static PDF graphics stream.
  2. Render the pre-flattened bytes onto a 200 DPI canvas via pdf.js with annotationMode: 1 (ENABLE, which also paints sticky notes, highlights, and freehand ink annotations directly onto the canvas), embed each rendered page into a fresh PDFDocument, scrub metadata, and save with updateFieldAppearances: false to produce a single 1 %%EOF file.

Walkthrough Video

Watch the 45-second browser-local walkthrough: https://www.youtube.com/watch?v=FpFixZDjVsE

Try It Directly in Your Browser (Zero Uploads)

We built this full inspection, Vector Flatten, 200 DPI Image Flatten, and metadata scrubbing engine into PDFFields Flatten PDF.

  • Free instant diagnostic: Drop any PDF (or load our built-in 10-field W-9 sample) to inspect every AcroForm field, annotation, /Info and XMP metadata tag, and %%EOF revision count locally with zero uploads.
  • Free before-and-after flattened preview: Switch between Vector Flatten and 200 DPI Full-Page Image Flatten and verify 0 editable fields, 0 metadata tags, and 1 %%EOF revision before exporting.
  • Need to audit blacked-out redactions first? Pair it with our free local PDF Redaction Leak Checker to make sure no hidden characters remain underneath black rectangles.

Originally published at pdffields.com/flatten-pdf.

πŸ“° Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.