Skip to content

PDF Internals and Extraction

SIDHARTH SINGH edited this page Dec 3, 2026 · 1 revision

PDF Internals, Optimization & Structural Extraction

Everything inside src/pdf/, src/optimize/, src/merge/, src/inspect/, and src/extract/ executes natively in TypeScript without external PDF binaries.

Forensic Tolerant Parsing & Dual-Layout Writing

  • Parser (src/pdf/parser.ts): Handles broken /Length numbers via endstream scans, trims stray trailing bytes on deflate decompression, resolves PNG row predictors, chases classic and cross-reference stream /Prev chains cleanly, locates incremental updates in the final 4,096 bytes, and falls back to recoverByScan() when xref tables are corrupted.
  • Optimizer (src/optimize/): Runs four progressive compaction tiers (none, fast, balanced, maximum). At balanced (default), reachability GC, semantic SHA-256 stream deduplication (decoded bytes + metadata excluding /Length and /Filter), 3-pass object deduplication, object stream packing (ObjStm), and empirical dual-layout comparison shrink Chromium output typically by 17–21% while keeping every text span searchable.

Geometry-Driven Extraction & Scan Diagnostics

  • Text & Coordinate Runs (extractText(), extractPositionedText()): Tracks graphics CTM stacks and font matrices, recursing into Form XObjects up to depth 8, resolving /ActualText tags (preserving emoji sequences cleanly), and auto-scoring 1-byte vs 2-byte CID mappings.
  • Tables & Indian GST Invoices (extractTables(), extractInvoiceData(), isValidGstin()): Clusters aligned columns using negative TJ kerning splits without breaking blank middle cells, merges multi-page tables by deduplicating repeating column headers, parses INR totals cleanly without confusing Sub Totals with Grand Totals, and runs the Mod-36 Luhn checksum on 15-character GSTINs.
  • Scan Quality (inspectScanQuality()): Classifies uploads as 'searchable', 'scanned', 'hybrid', or 'empty', flags estimated DPI under 150 DPI, highlights oversized image streams, and checks the common < 200 KB GovTech portal cap.

Clone this wiki locally