/** * pdf-extract.ts — 自写最小 PDF 解析器(离线、零第三方依赖)。 * * 目标:从增值税电子发票(数电票/全电发票)PDF 中提取 * 1. 内嵌结构化 XML 附件(优先,/EmbeddedFiles 命名树,支持 FlateDecode 或未压缩流); * 2. 文本层(页面 Content 流的 BT..ET 文本操作符,Tj/TJ;支持 latin1 与 UTF-16BE hex 字符串); * 3. 加密/密码保护检测(/Encrypt)。 * * 实现手段:不依赖 xref 表——按顺序扫描 `N G obj` 定义并用 /Length 精确跳过 * stream 内容(与真实 pdfplumber/pypdf 抽取结果等价的轻量实现),因此对 * 传统 xref 表与 xref 流(真实数电票常见)均鲁棒。仅使用 Node 内置 zlib。 * * 局限(README 明示):不支持 JPEG2000/对象流内的间接引用流、不渲染页面; * 生产环境如需完整 PDF 语义可替换为调用 pdfplumber/pypdf 的外部路径。 */ import { deflateSync, inflateRawSync, inflateSync } from 'node:zlib' /** PDF 抽取结果。 */ export interface PdfExtraction { /** 拼合后的文本层(每"行文本"以 \n 分隔)。 */ text: string /** 内嵌附件中解码出的 XML 文档(按附件出现顺序)。 */ embeddedXml: string[] /** PDF 是否声明了 /Encrypt(密码保护/加密)。 */ encrypted: boolean /** 页面数量(尽量统计;无法确定时为 0)。 */ pageCount: number } // --------------------------------------------------------------------------- // 字节工具 // --------------------------------------------------------------------------- /** 字节 → latin1 字符串(逐字节一一映射,作为定位/词法视图)。 */ function bytesToLatin1(bytes: Uint8Array): string { let out = '' const chunk = 0x8000 for (let i = 0; i < bytes.length; i += chunk) { const end = Math.min(i + chunk, bytes.length) out += String.fromCharCode(...bytes.subarray(i, end)) } return out } /** latin1 字符串 → 字节。 */ function latin1ToBytes(str: string): Uint8Array { const bytes = new Uint8Array(str.length) for (let i = 0; i < str.length; i++) bytes[i] = str.charCodeAt(i) & 0xff return bytes } /** latin1 解码。 */ function decodeLatin1(bytes: Uint8Array): string { let out = '' for (let i = 0; i < bytes.length; i++) out += String.fromCharCode(bytes[i]) return out } /** 尝试多种解码:优先 UTF-16BE(带 BOM),否则 latin1。 */ function decodePossiblyUtf16(bytes: Uint8Array): string { if (bytes.length >= 2 && bytes[0] === 0xfe && bytes[1] === 0xff) { const out: string[] = [] for (let i = 2; i + 1 < bytes.length; i += 2) { out.push(String.fromCharCode((bytes[i] << 8) | bytes[i + 1])) } return out.join('') } return decodeLatin1(bytes) } // --------------------------------------------------------------------------- // PDF 值词法 // --------------------------------------------------------------------------- type PdfValue = | { kind: 'name'; name: string } | { kind: 'string'; text: string } | { kind: 'number'; num: number } | { kind: 'ref'; num: number; gen: number } | { kind: 'array'; items: PdfValue[] } | { kind: 'dict'; dict: Record } | { kind: 'bool'; value: boolean } | { kind: 'null' } function isName(v: PdfValue | undefined, name: string): boolean { return v !== undefined && v.kind === 'name' && v.name === name } function nameOf(v: PdfValue | undefined): string | undefined { return v !== undefined && v.kind === 'name' ? v.name : undefined } function stringOf(v: PdfValue | undefined): string | undefined { return v !== undefined && v.kind === 'string' ? v.text : undefined } function numberOf(v: PdfValue | undefined): number | undefined { return v !== undefined && v.kind === 'number' ? v.num : undefined } /** 解析 PDF 普通字符串 (..),处理 \n \r \t \b \f \( \) \\ 与 \ddd 八进制。 */ function parsePdfString(str: string, start: number): { text: string; end: number } { let i = start + 1 // 跳过 ( const out: string[] = [] while (i < str.length) { const c = str[i] if (c === ')') return { text: out.join(''), end: i + 1 } if (c === '\\') { const n = str[i + 1] switch (n) { case 'n': out.push('\n'); i += 2; break case 'r': out.push('\r'); i += 2; break case 't': out.push('\t'); i += 2; break case 'b': out.push('\b'); i += 2; break case 'f': out.push('\f'); i += 2; break case '(': out.push('('); i += 2; break case ')': out.push(')'); i += 2; break case '\\': out.push('\\'); i += 2; break case '\r': i += str[i + 1] === '\n' ? 2 : 1 break case '\n': i += 1 break default: { // \ddd 八进制(1-3 位) let codeStr = '' let j = i + 1 while (j < str.length && codeStr.length < 3 && str[j] >= '0' && str[j] <= '7') { codeStr += str[j] j++ } if (codeStr.length > 0) { out.push(String.fromCharCode(parseInt(codeStr, 8) & 0xff)) i = j } else { i += 2 } } } } else { out.push(c) i++ } } return { text: out.join(''), end: str.length } } /** * 解析一个 PDF 值(从 pos 处开始)。支持 name/string/hex-string/array/dict/number/ref/bool/null。 * 返回 { value, end };无法识别类型时返回 { value: undefined, end: pos }。 */ function parsePdfValueAt(str: string, pos: number): { value: PdfValue | undefined; end: number } { const skipWs = (p: number): number => { while (p < str.length && /[\x00-\x20]/.test(str[p])) p++ return p } let p = skipWs(pos) const c = str[p] if (c === '/') { const m = /^[A-Za-z0-9._\-!#$&*+,:;=?@|~]+/.exec(str.slice(p + 1)) if (!m) return { value: undefined, end: p } return { value: { kind: 'name', name: m[0] }, end: p + 1 + m[0].length } } if (c === '(') { const r = parsePdfString(str, p) return { value: { kind: 'string', text: r.text }, end: r.end } } if (c === '<') { if (str[p + 1] === '<') { // 嵌套字典:包装为 { value: { kind: 'dict', ... }, end },不能直接透传 parsePdfDictAt 的返回形状 const d = parsePdfDictAt(str, p) return d.dict === undefined ? { value: undefined, end: d.end } : { value: { kind: 'dict', dict: d.dict }, end: d.end } } // hex string <...> const close = str.indexOf('>', p + 1) if (close < 0) return { value: undefined, end: p } const hex = str.slice(p + 1, close).replace(/[\s]/g, '') const bytes = new Uint8Array(Math.ceil(hex.length / 2)) for (let i = 0; i < bytes.length; i++) { const h = hex.slice(i * 2, i * 2 + 2) bytes[i] = parseInt(h.padEnd(2, '0'), 16) || 0 } return { value: { kind: 'string', text: decodePossiblyUtf16(bytes) }, end: close + 1 } } if (c === '[') { const items: PdfValue[] = [] let q = p + 1 for (;;) { q = skipWs(q) if (q >= str.length) return { value: undefined, end: q } if (str[q] === ']') return { value: { kind: 'array', items }, end: q + 1 } const r = parsePdfValueAt(str, q) if (r.value === undefined) q = skipWs(q + 1) else { items.push(r.value) q = r.end } } } if (c === 't' && str.startsWith('true', p)) return { value: { kind: 'bool', value: true }, end: p + 4 } if (c === 'f' && str.startsWith('false', p)) return { value: { kind: 'bool', value: false }, end: p + 5 } if (c === 'n' && str.startsWith('null', p)) return { value: { kind: 'null' }, end: p + 4 } if (c === '-' || c === '+' || c === '.' || (c >= '0' && c <= '9')) { const m = /^[+-]?(\d+(?:\.\d+)?)(?=[\s\]\/>])/.exec(str.slice(p)) if (!m) return { value: undefined, end: p } const raw = m[0] const after = skipWs(p + raw.length) // 间接引用形式 "N G R":raw 是 N,后面再跟一个整数 G 与 R const refM = /^(\d+)\s+R/.exec(str.slice(after)) if (refM) { return { value: { kind: 'ref', num: parseFloat(raw), gen: parseInt(refM[1], 10) }, end: after + refM[0].length } } if (str[after] === 'R') { return { value: { kind: 'ref', num: parseFloat(raw), gen: 0 }, end: after + 1 } } return { value: { kind: 'number', num: parseFloat(raw) }, end: p + raw.length } } return { value: undefined, end: p } } /** 解析 PDF 字典 << ... >>,返回 { dict, end };非字典起始时返回 { dict: undefined, end: pos }。 */ function parsePdfDictAt(str: string, pos: number): { dict: Record | undefined; end: number } { const skipWs = (p: number): number => { while (p < str.length && /[\x00-\x20]/.test(str[p])) p++ return p } let p = skipWs(pos) if (!str.startsWith('<<', p)) return { dict: undefined, end: p } const dict: Record = {} p = skipWs(p + 2) for (;;) { if (p >= str.length) return { dict: undefined, end: str.length } // 闭合 >> 处返回 if (str[p] === '>' && str[p + 1] === '>') return { dict, end: p + 2 } // 期望 key(/Name);异常容错:前进到下一个 '/' 或闭合 '>>' if (str[p] !== '/') { const nextSlash = str.indexOf('/', p + 1) const nextClose = str.indexOf('>>', p) if (nextClose >= 0 && (nextSlash < 0 || nextClose < nextSlash)) { p = nextClose continue } if (nextSlash >= 0) { p = nextSlash continue } return { dict: undefined, end: str.length } } const keyMatch = /^[A-Za-z0-9._\-!#$&*+,:;=?@|~]+/.exec(str.slice(p + 1)) if (!keyMatch) return { dict: undefined, end: p } const key = keyMatch[0] p = skipWs(p + 1 + key.length) const r = parsePdfValueAt(str, p) if (r.value === undefined) { // 缺值:跳到下一个 '/' 继续 const nextSlash = str.indexOf('/', p + 1) if (nextSlash < 0) return { dict: undefined, end: str.length } p = nextSlash continue } dict[key] = r.value p = skipWs(r.end) } } // --------------------------------------------------------------------------- // 顶层扫描与流提取 // --------------------------------------------------------------------------- interface ScannedObject { num: number gen: number /** 对象 dict(可能无)。 */ dict?: Record /** stream 数据字节区间(-1 表示非流对象)。 */ streamStart: number streamEnd: number /** 对象开始偏移。 */ start: number } const WS_RE = /^[\x00-\x20\r\n\t\f]*/ /** 在 latin1 视图中查找 "stream" 关键字并返回流字节起始(跳过 CRLF)。 * limit 用于约束"紧邻字典之后"的位置,避免误把远处对象的 stream 关键字当成本对象的。 */ function findStreamStart(latin: string, from: number, limit?: number): number { const idx = latin.indexOf('stream', from) if (idx < 0) return -1 if (limit !== undefined && idx > from + limit) return -1 let p = idx + 'stream'.length if (latin[p] === '\r') p++ if (latin[p] === '\n') p++ return p } /** * 顺序扫描全部顶层对象。用 /Length(直接数字)或 "下一个 endstream" 定位流边界, * 从而跳过流内容,规避流内 "N G obj" 误报。 */ function scanObjects(bytes: Uint8Array): ScannedObject[] { const latin = bytesToLatin1(bytes) const objs: ScannedObject[] = [] const RE = /(\d{1,6})\s+(\d{1,6})\s+obj/g let skipUntil = 0 let m: RegExpExecArray | null while ((m = RE.exec(latin)) !== null) { const start = m.index if (start < skipUntil) { RE.lastIndex = Math.max(RE.lastIndex, skipUntil) continue } const num = parseInt(m[1], 10) const gen = parseInt(m[2], 10) // 解析对象体:dict 或标量 const dictStart = m.index + m[0].length const head = latin.slice(dictStart).replace(WS_RE, '') const headOffset = dictStart + (latin.slice(dictStart).length - head.length) const dictResult = /^<= 0) { // 有 stream:长度优先用 /Length,其次找 endstream let length = numberOf(dictResult.dict['Length']) if (length !== undefined && length >= 0) { streamStart = streamPos streamEnd = streamPos + length nextPos = streamEnd } else { const es = latin.indexOf('endstream', streamPos) streamStart = streamPos streamEnd = es >= 0 ? es : streamPos nextPos = es >= 0 ? es : streamPos } if (length === undefined) { // /Length 引用或缺失:确认 endstream 紧跟在流后 const es = latin.indexOf('endstream', streamEnd) if (es >= 0 && es - streamEnd <= 4) nextPos = es } } else { nextPos = dictResult.end } objs.push({ num, gen, dict: dictResult.dict, streamStart, streamEnd, start }) // 跳过流内容,防止误报 skipUntil = streamEnd > 0 ? streamEnd + 10 : dictResult.end + 8 } else { // 标量对象:跳到 endobj const endobj = latin.indexOf('endobj', headOffset) nextPos = endobj >= 0 ? endobj : headOffset + 8 objs.push({ num, gen, streamStart, streamEnd, start }) skipUntil = nextPos + 8 } if (RE.lastIndex < nextPos) RE.lastIndex = Math.max(RE.lastIndex + 1, nextPos) } // 归并重复编号(取最后一个出现的对象,通常最完整) const byNum = new Map() for (const obj of objs) byNum.set(obj.num, obj) return [...byNum.values()].sort((a, b) => a.start - b.start) } /** 获取指定对象号的流字节(若为流对象)。 */ function getStreamBytes(bytes: Uint8Array, objs: ScannedObject[], num: number): Uint8Array | undefined { const obj = objs.find((o) => o.num === num) if (!obj || obj.streamStart < 0 || obj.streamEnd <= obj.streamStart) return undefined return bytes.subarray(Math.max(0, obj.streamStart), Math.min(bytes.length, obj.streamEnd)) } /** 按 /Filter 链解码流(支持 FlateDecode / Fl / Flate;失败时回退原样)。 */ function decodeStream(bytes: Uint8Array): Uint8Array { try { return inflateSync(bytes) } catch { try { return inflateRawSync(bytes) } catch { return bytes } } } function filterChainOf(dict: Record | undefined): string[] { if (!dict) return [] const f = dict['Filter'] if (!f) return [] if (f.kind === 'name') return [f.name] if (f.kind === 'array') return f.items.filter((x) => x.kind === 'name').map((x) => (x as { name: string }).name) return [] } function applyFilterChain(bytes: Uint8Array, filters: string[]): Uint8Array { let data = bytes for (const f of filters) { // 本版仅实现 FlateDecode;未知过滤器保持原样(上层会对不可解码内容降级处理) if (f === 'FlateDecode' || f === 'Fl') data = decodeStream(data) } return data } function dictValueText(v: PdfValue | undefined): string { if (!v) return '' if (v.kind === 'string' || v.kind === 'name') return v.kind === 'string' ? v.text : v.name if (v.kind === 'number') return String(v.num) return '' } // --------------------------------------------------------------------------- // 内容流文本抽取 // --------------------------------------------------------------------------- /** * 从单个页面 Content 流文本中抽取文本行。 * 词法:BT..ET 块内收集字符串操作数(latin1 或 hex UTF-16BE 已在上层规整), * Tj 与 TJ 输出;Td、TD、T*、Tm 视为换行分隔。 */ function extractContentText(contentLatin: string): string { const lines: string[] = [] let pos = 0 while (pos < contentLatin.length) { const bt = contentLatin.indexOf('BT', pos) if (bt < 0) break const et = contentLatin.indexOf('ET', bt + 2) if (et < 0) break pos = et + 2 const block = contentLatin.slice(bt + 2, et) // tokenize:字符串 / 数组(递归)/ 数字 / 名字 / 操作符 const tokens: ({ kind: 'str'; value: string } | { kind: 'arr'; value: string[] } | { kind: 'op'; value: string })[] = [] let i = 0 while (i < block.length) { const c = block[i] if (c === '%') { const nl = block.indexOf('\n', i) i = nl < 0 ? block.length : nl + 1 continue } if (/[\x00-\x20]/.test(c)) { i++; continue } if (c === '(') { const r = parsePdfString(block, i) tokens.push({ kind: 'str', value: r.text }) i = r.end continue } if (c === '<') { // hex string const close = block.indexOf('>', i + 1) if (close < 0) break const hex = block.slice(i + 1, close).replace(/[\s]/g, '') const b = new Uint8Array(Math.ceil(hex.length / 2)) for (let k = 0; k < b.length; k++) { const h = hex.slice(k * 2, k * 2 + 2) b[k] = parseInt(h.padEnd(2, '0'), 16) || 0 } tokens.push({ kind: 'str', value: decodePossiblyUtf16(b) }) i = close + 1 continue } if (c === '[') { const items: string[] = [] let j = i + 1 while (j < block.length && block[j] !== ']') { if (block[j] === '(') { const r = parsePdfString(block, j) items.push(r.text) j = r.end } else if (/^<[0-9A-Fa-f\s]+>$/.test(block.slice(j, block.indexOf('>', j) + 1))) { const close = block.indexOf('>', j) const hex = block.slice(j + 1, close).replace(/[\s]/g, '') const b = new Uint8Array(Math.ceil(hex.length / 2)) for (let k = 0; k < b.length; k++) { const h = hex.slice(k * 2, k * 2 + 2) b[k] = parseInt(h.padEnd(2, '0'), 16) || 0 } items.push(decodePossiblyUtf16(b)) j = close + 1 } else { j++ } } tokens.push({ kind: 'arr', value: items }) i = j + 1 continue } if (c === '/') { const m = /^[A-Za-z0-9._\-]+/.exec(block.slice(i + 1)) if (!m) { i++; continue } i = i + 1 + m[0].length continue } if (c === '-' || c === '+' || c === '.' || (c >= '0' && c <= '9')) { const m = /^[+-]?[\d.]+/.exec(block.slice(i)) if (m) i += m[0].length else i++ continue } // 操作符(字母序列) const m = /^[A-Za-z*'"]+/.exec(block.slice(i)) if (m) { tokens.push({ kind: 'op', value: m[0] }) i += m[0].length } else i++ } // 依操作符装配文本行 let pending: string[] = [] let pendingArr: string[] | null = null const flush = () => { if (pending.length > 0 || (pendingArr !== null && pendingArr.length > 0)) { const joined = pendingArr !== null ? pendingArr.join('') : pending.join('') if (joined.length > 0) lines.push(joined) } pending = [] pendingArr = null } for (let k = 0; k < tokens.length; k++) { const tkn = tokens[k] if (tkn.kind === 'str') pending.push(tkn.value) else if (tkn.kind === 'arr') pendingArr = tkn.value else { const op = tkn.value as string if (op === 'Tj') flush() else if (op === 'TJ') flush() else if (op === 'Td' || op === 'TD' || op === 'T*' || op === 'Tm') { flush() // 末尾标记新行(下一段文本前) pending = [] } else if (op === 'ET') flush() } } flush() } return lines.join('\n') } // --------------------------------------------------------------------------- // EmbeddedFiles 附件提取 // --------------------------------------------------------------------------- /** 从扫描对象中提取 /EmbeddedFiles 命名树里的全部附件(name → 文本内容)。 */ function extractEmbeddedXml(bytes: Uint8Array, objs: ScannedObject[]): { name: string; text: string }[] { const out: { name: string; text: string }[] = [] for (const obj of objs) { if (!obj.dict) continue // /EmbeddedFiles 可能直接挂在对象下(如 Catalog 的 /Names 子树内) let embedded: PdfValue | undefined = obj.dict['EmbeddedFiles'] if (embedded === undefined || embedded.kind === 'null') { const names = obj.dict['Names'] embedded = names !== undefined && names.kind === 'dict' ? names.dict['EmbeddedFiles'] : undefined } if (!embedded || embedded.kind === 'null') continue if (embedded.kind === 'dict') { // 命名树:/Names [ (a) ref (b) ref ... ] const namesArr = embedded.dict['Names'] if (!namesArr || namesArr.kind !== 'array') continue const items = namesArr.items for (let k = 0; k + 1 < items.length; k += 2) { const nameVal = items[k] const refVal = items[k + 1] const fileName = stringOf(nameVal) ?? nameOf(nameVal) ?? '' if (refVal.kind !== 'ref') continue const filespec = objs.find((o) => o.num === refVal.num) if (!filespec || !filespec.dict) continue const ef = filespec.dict['EF'] if (!ef || ef.kind !== 'dict') continue const fRef = ef.dict['F'] if (!fRef || fRef.kind !== 'ref') continue const fileObj = objs.find((o) => o.num === fRef.num) if (!fileObj) continue const raw = getStreamBytes(bytes, objs, fRef.num) if (!raw) continue const bytes2 = applyFilterChain(raw, filterChainOf(fileObj.dict)) // 附件可能是 XML 文本;逐字节丢非法 UTF-8 序列,宽松解码 const text = bytesToUtf8Lossy(bytes2) if (text.trim().length > 0) out.push({ name: fileName, text }) } } } return out } /** 宽松 UTF-8 解码(非法序列替换为 U+FFFD)。 */ function bytesToUtf8Lossy(bytes: Uint8Array): string { try { return new TextDecoder('utf-8', { fatal: false }).decode(bytes) } catch { return decodeLatin1(bytes) } } // --------------------------------------------------------------------------- // 入口 // --------------------------------------------------------------------------- /** 解析 PDF 字节:文本层 + XML 附件 + 加密/页数元信息。 */ export function extractPdf(bytes: Uint8Array): PdfExtraction { const latin = bytesToLatin1(bytes) const objs = scanObjects(bytes) // 加密检测:任何对象 dict 或 trailer 含 /Encrypt let encrypted = false const trailerIdx = latin.lastIndexOf('trailer') const trailerDict = trailerIdx >= 0 ? parsePdfDictAt(latin, latin.indexOf('<<', trailerIdx)) : undefined if (trailerDict && trailerDict.dict && trailerDict.dict['Encrypt']) encrypted = true for (const obj of objs) { if (encrypted) break if (obj.dict && obj.dict['Encrypt']) encrypted = true } // 文本层:收集所有 /Type /Page 的 /Contents 流 const pageNums: number[] = [] for (const obj of objs) { if (obj.dict && isName(obj.dict['Type'], 'Page')) pageNums.push(obj.num) } const pageTexts: string[] = [] for (const pageNum of pageNums) { const page = objs.find((o) => o.num === pageNum) if (!page || !page.dict) continue const contents = page.dict['Contents'] const refs: number[] = [] if (contents && contents.kind === 'ref') refs.push(contents.num) else if (contents && contents.kind === 'array') { for (const item of contents.items) if (item.kind === 'ref') refs.push(item.num) } for (const ref of refs) { const raw = getStreamBytes(bytes, objs, ref) if (!raw) continue const decoded = applyFilterChain(raw, filterChainOf(objs.find((o) => o.num === ref)?.dict)) const text = extractContentText(decodePossiblyUtf16(decoded)) if (text.length > 0) pageTexts.push(text) } } const text = pageTexts.join('\n').trim() // XML 附件 const xmls = extractEmbeddedXml(bytes, objs).map((x) => x.text) return { text, embeddedXml: xmls, encrypted, pageCount: pageNums.length } } /** 判断文件类型(读头字节,避免整读):pdf / png / jpg / other。 */ export function detectFileKind(bytes: Uint8Array, fileName: string): 'pdf' | 'png' | 'jpg' | 'other' { const base = fileName.toLowerCase() const isPdfMagic = bytes.length >= 5 && bytes[0] === 0x25 && bytes[1] === 0x50 && bytes[2] === 0x44 && bytes[3] === 0x46 && bytes[4] === 0x2d if (isPdfMagic) return 'pdf' if (bytes.length >= 8 && bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47) return 'png' if (bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return 'jpg' if (base.endsWith('.pdf')) return 'pdf' if (base.endsWith('.png')) return 'png' if (base.endsWith('.jpg') || base.endsWith('.jpeg')) return 'jpg' return 'other' } /** 供测试与生产复用:把 UTF-8 文本压缩进 PDF 流所需的 Flate 编码(保持对称,供 fixture 生成器使用)。 */ export { deflateSync as deflateFlate }