* Extract text from PDF content stream operators. * Handles: (text) Tj, [(text)] TJ, Td/Tm for positioning
(stream)
| 80 | * Handles: (text) Tj, [(text)] TJ, Td/Tm for positioning |
| 81 | */ |
| 82 | function extractTextOps(stream) { |
| 83 | const lines = []; |
| 84 | let currentLine = ''; |
| 85 | |
| 86 | // Match BT...ET blocks (text objects) |
| 87 | const btBlocks = stream.match(/BT[\s\S]*?ET/g); |
| 88 | if (!btBlocks) return ''; |
| 89 | |
| 90 | for (const block of btBlocks) { |
| 91 | // (string) Tj — show string |
| 92 | const tjMatches = block.matchAll(/\(([^)]*)\)\s*Tj/g); |
| 93 | for (const m of tjMatches) { |
| 94 | currentLine += decodePdfString(m[1]); |
| 95 | } |
| 96 | |
| 97 | // [...] TJ — show strings with spacing |
| 98 | const tjArrayMatches = block.matchAll(/\[((?:[^[\]]*|\([^)]*\))*)\]\s*TJ/gi); |
| 99 | for (const m of tjArrayMatches) { |
| 100 | const inner = m[1]; |
| 101 | const parts = inner.matchAll(/\(([^)]*)\)|(-?\d+(?:\.\d+)?)/g); |
| 102 | for (const p of parts) { |
| 103 | if (p[1] !== undefined) { |
| 104 | currentLine += decodePdfString(p[1]); |
| 105 | } else if (p[2] !== undefined) { |
| 106 | const kern = parseFloat(p[2]); |
| 107 | if (kern < -100) currentLine += ' '; |
| 108 | } |
| 109 | } |
| 110 | } |
| 111 | |
| 112 | // Td/TD/Tm — text positioning (new line heuristic) |
| 113 | if (/\d+\s+(?:-?\d+(?:\.\d+)?)\s+T[dD]/g.test(block)) { |
| 114 | if (currentLine.trim()) { |
| 115 | lines.push(currentLine.trim()); |
| 116 | currentLine = ''; |
| 117 | } |
| 118 | } |
| 119 | } |
| 120 | |
| 121 | if (currentLine.trim()) lines.push(currentLine.trim()); |
| 122 | return lines.join('\n'); |
| 123 | } |
| 124 | |
| 125 | /** |
| 126 | * Decode PDF string escapes: \n, \r, \t, \\, \(, \), octal |
no test coverage detected