import { inflateSync } from 'node:zlib' /** * A reader of the files the core's writer produces (R4.8: pdf-lib left the application * and its tests; `crates/core/src/pdf/write/{objects,serialize}.rs` is the format). Test * tooling only, on trusted bytes the tests just wrote: every object is `N 0 obj`, one * dictionary on one line (`<< /Key value … >>`, nested dictionaries inline, strings in hex), * an optional `stream` of the direct `/Length` bytes, then `endobj`; the page tree is one * `/Pages` node whose `/Kids` lists the pages in order. Nothing here parses a foreign PDF: * the application reads attachments with the core's scanner. */ export interface PdfObject { number: number /** The dictionary text, `<<` to `>>` inclusive. */ dict: string /** The raw stream bytes (not inflated), when the object is a stream. */ stream: Uint8Array | null } const latin1 = new TextDecoder('latin1') /** The end of the dictionary that opens at `start` (`<<`): strings and nesting skipped. */ function dictEnd(text: string, start: number): number { let depth = 0 let at = start while (at < text.length) { const two = text.slice(at, at + 2) if (two === '<<') { depth += 1 at += 2 } else if (two === '>>') { depth -= 1 at += 2 if (depth === 0) return at } else if (text[at] === '<') { at = text.indexOf('>', at) + 1 } else if (text[at] === '(') { at = text.indexOf(')', at) + 1 } else { at += 1 } } throw new Error('unterminated dictionary') } function lengthOf(dict: string): number { const match = /\/Length (\d+)/.exec(dict) if (!match) throw new Error('stream without /Length') return Number(match[1]) } /** The objects of the file, by number. */ export function parsePdf(bytes: Uint8Array): Map { const text = latin1.decode(bytes) const objects = new Map() const header = /(\d+) 0 obj\n/g let match: RegExpExecArray | null while ((match = header.exec(text)) !== null) { const number = Number(match[1]) const start = header.lastIndex if (text.slice(start, start + 2) !== '<<') continue const end = dictEnd(text, start) const dict = text.slice(start, end) let stream: Uint8Array | null = null const marker = '\nstream\n' if (text.slice(end, end + marker.length) === marker) { const from = end + marker.length stream = bytes.slice(from, from + lengthOf(dict)) header.lastIndex = from + stream.length } objects.set(number, { number, dict, stream }) } return objects } /** The decoded stream of an object: inflated when `/Filter /FlateDecode`. */ export function streamOf(object: PdfObject): Uint8Array { if (!object.stream) throw new Error(`object ${object.number} is not a stream`) return object.dict.includes('/Filter /FlateDecode') ? new Uint8Array(inflateSync(object.stream)) : object.stream } /** The text of a nested dictionary value (`/Key << … >>`). */ export function subDict(dict: string, key: string): string | null { const at = dict.indexOf(`/${key} <<`) if (at < 0) return null const start = at + key.length + 2 return dict.slice(start, dictEnd(dict, start)) } /** `/Key N 0 R` → N. */ export function refOf(dict: string, key: string): number | null { const match = new RegExp(`/${key} (\\d+) 0 R`).exec(dict) return match ? Number(match[1]) : null } /** `/Key [N 0 R M 0 R …]` → [N, M, …]. */ export function refsOf(dict: string, key: string): number[] { const match = new RegExp(`/${key} \\[([^\\]]*)\\]`).exec(dict) if (!match) return [] return [...match[1]!.matchAll(/(\d+) 0 R/g)].map((m) => Number(m[1])) } /** `/Key /Name` → Name. */ export function nameOf(dict: string, key: string): string | null { const match = new RegExp(`/${key} /([^\\s/>]+)`).exec(dict) return match ? match[1]! : null } export function numberOf(dict: string, key: string): number | null { const match = new RegExp(`/${key} (-?[\\d.]+)`).exec(dict) return match ? Number(match[1]) : null } /** `/Key [n n n n]` → the numbers. */ export function numbersOf(dict: string, key: string): number[] { const match = new RegExp(`/${key} \\[([^\\]]*)\\]`).exec(dict) return match ? match[1]!.trim().split(/\s+/).map(Number) : [] } /** A hex string `<…>`: UTF-16BE behind a BOM, else Latin-1 bytes. */ export function decodeHexString(token: string): string { const hex = token.slice(1, -1) const bytes = new Uint8Array(hex.length / 2) for (let i = 0; i < bytes.length; i += 1) { bytes[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16) } if (bytes[0] === 0xfe && bytes[1] === 0xff) { return new TextDecoder('utf-16be').decode(bytes.subarray(2)) } return latin1.decode(bytes) } /** `/Key ` or `/Key (literal)` → the decoded text. */ export function textOf(dict: string, key: string): string | null { const match = new RegExp(`/${key} (<[0-9A-Fa-f]*>|\\([^)]*\\))`).exec(dict) if (!match) return null const token = match[1]! return token.startsWith('<') ? decodeHexString(token) : token.slice(1, -1) } /** `/F1 5 0 R /F2 6 0 R` → the name → object number pairs of a resource dictionary. */ export function entriesOf(dict: string): Map { return new Map( [...dict.matchAll(/\/([^\s/<>]+) (\d+) 0 R/g)].map((m) => [ m[1]!, Number(m[2]), ]), ) } /** The file as a whole: its objects, catalog, pages in order, Info. */ export class PdfFile { private constructor( private readonly objects: Map, private readonly trailer: string, ) {} static parse(bytes: Uint8Array): PdfFile { const text = latin1.decode(bytes) const at = text.lastIndexOf('trailer\n') if (at < 0) throw new Error('no trailer') return new PdfFile(parsePdf(bytes), text.slice(at)) } object(number: number): PdfObject { const object = this.objects.get(number) if (!object) throw new Error(`object ${number} missing`) return object } /** Every object, in number order. */ all(): PdfObject[] { return [...this.objects.values()].sort((a, b) => a.number - b.number) } catalog(): PdfObject { return this.object(refOf(this.trailer, 'Root')!) } info(): PdfObject { return this.object(refOf(this.trailer, 'Info')!) } /** The pages in `/Kids` order. */ pages(): PdfObject[] { const pages = this.object(refOf(this.catalog().dict, 'Pages')!) return refsOf(pages.dict, 'Kids').map((n) => this.object(n)) } /** The content stream text (Latin-1) of a page. */ content(page: PdfObject): string { return latin1.decode(streamOf(this.object(refOf(page.dict, 'Contents')!))) } /** `/F1` → `Helvetica`, through the page's font resources. */ fontNames(page: PdfObject): Map { const fonts = subDict(subDict(page.dict, 'Resources') ?? '', 'Font') ?? '' const names = new Map() for (const [name, number] of entriesOf(fonts)) { names.set(name, nameOf(this.object(number).dict, 'BaseFont') ?? '') } return names } /** The image XObjects of a page, by resource name. */ xobjects(page: PdfObject): Map { const dict = subDict(subDict(page.dict, 'Resources') ?? '', 'XObject') ?? '' return new Map( [...entriesOf(dict)].map(([name, number]) => [name, this.object(number)]), ) } /** The annotation objects of a page, in `/Annots` order. */ annots(page: PdfObject): PdfObject[] { return refsOf(page.dict, 'Annots').map((n) => this.object(n)) } } /** * A minimal PDF carrying one embedded file in clear (one empty page, the stream stored * raw, a Filespec named `/F (name)` with `/EF`, the names tree, a classic xref): what the * rejection cases of the import suites used to build with pdf-lib. Test input only. */ export function buildPdfWithAttachment( name: string, data: Uint8Array, ): Uint8Array { const latin1Bytes = (text: string) => Uint8Array.from(text, (c) => c.charCodeAt(0)) const bodies: Uint8Array[] = [ latin1Bytes( `<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles << /Names [(${name}) 5 0 R] >> >> >>`, ), latin1Bytes('<< /Type /Pages /Count 1 /Kids [3 0 R] >>'), latin1Bytes( '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595.28 841.89] >>', ), new Uint8Array([ ...latin1Bytes( `<< /Type /EmbeddedFile /Subtype /application#2Fjson /Length ${data.length} >>\nstream\n`, ), ...data, ...latin1Bytes('\nendstream'), ]), latin1Bytes( `<< /Type /Filespec /F (${name}) /UF (${name}) /EF << /F 4 0 R >> /AFRelationship /Data >>`, ), ] const parts: Uint8Array[] = [latin1Bytes('%PDF-1.7\n%\xe2\xe3\xcf\xd3\n')] const offsets: number[] = [] let total = parts[0]!.length bodies.forEach((body, i) => { offsets.push(total) const object = new Uint8Array([ ...latin1Bytes(`${i + 1} 0 obj\n`), ...body, ...latin1Bytes('\nendobj\n'), ]) parts.push(object) total += object.length }) const xref = [ 'xref', `0 ${bodies.length + 1}`, '0000000000 65535 f ', ...offsets.map((o) => `${String(o).padStart(10, '0')} 00000 n `), 'trailer', `<< /Size ${bodies.length + 1} /Root 1 0 R >>`, 'startxref', String(total), '%%EOF', '', ].join('\n') parts.push(latin1Bytes(xref)) const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0)) let at = 0 for (const part of parts) { out.set(part, at) at += part.length } return out }