|
| 1 | +#!/usr/bin/env -S deno run --allow-read --allow-env |
| 2 | +/** |
| 3 | + * pdf-tag-tree.ts |
| 4 | + * |
| 5 | + * Extracts and displays the PDF structure tree (tag hierarchy) with MCIDs. |
| 6 | + * Useful for debugging ensurePdfTextPositions issues. |
| 7 | + * |
| 8 | + * Usage: deno run --allow-read --allow-env tools/pdf-tag-tree.ts <pdf-file> [search-text] |
| 9 | + */ |
| 10 | + |
| 11 | +import * as pdfjsLib from "npm:pdfjs-dist@4.4.168/legacy/build/pdf.mjs"; |
| 12 | + |
| 13 | +interface StructTreeContent { |
| 14 | + type: "content"; |
| 15 | + id: string; |
| 16 | +} |
| 17 | + |
| 18 | +interface StructTreeNode { |
| 19 | + role: string; |
| 20 | + children?: (StructTreeNode | StructTreeContent)[]; |
| 21 | + alt?: string; |
| 22 | + lang?: string; |
| 23 | +} |
| 24 | + |
| 25 | +interface TextMarkedContent { |
| 26 | + type: string; |
| 27 | + id?: string; |
| 28 | + tag?: string; |
| 29 | +} |
| 30 | + |
| 31 | +interface TextItem { |
| 32 | + str: string; |
| 33 | + transform: number[]; |
| 34 | + width: number; |
| 35 | + height: number; |
| 36 | +} |
| 37 | + |
| 38 | +function isStructTreeContent(child: any): child is StructTreeContent { |
| 39 | + return child && typeof child === "object" && child.type === "content"; |
| 40 | +} |
| 41 | + |
| 42 | +function isTextMarkedContent(item: any): item is TextMarkedContent { |
| 43 | + return "type" in item && typeof item.type === "string"; |
| 44 | +} |
| 45 | + |
| 46 | +// Build a map from MCID to the path of tags leading to it |
| 47 | +function buildMcidPaths( |
| 48 | + node: StructTreeNode, |
| 49 | + path: string[] = [], |
| 50 | + result: Map<string, { path: string[]; role: string; attrs: Record<string, any> }> = new Map() |
| 51 | +): Map<string, { path: string[]; role: string; attrs: Record<string, any> }> { |
| 52 | + const currentPath = [...path, node.role]; |
| 53 | + |
| 54 | + for (const child of node.children ?? []) { |
| 55 | + if (isStructTreeContent(child)) { |
| 56 | + // This is an MCID reference |
| 57 | + const attrs: Record<string, any> = {}; |
| 58 | + if (node.alt) attrs.alt = node.alt; |
| 59 | + if (node.lang) attrs.lang = node.lang; |
| 60 | + |
| 61 | + result.set(child.id, { |
| 62 | + path: currentPath, |
| 63 | + role: node.role, |
| 64 | + attrs |
| 65 | + }); |
| 66 | + } else { |
| 67 | + // Recurse into child structure nodes |
| 68 | + buildMcidPaths(child, currentPath, result); |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + return result; |
| 73 | +} |
| 74 | + |
| 75 | +// Pretty print the structure tree |
| 76 | +function printStructTree(node: StructTreeNode, indent: number = 0, maxDepth: number = 10): void { |
| 77 | + if (indent > maxDepth) { |
| 78 | + console.log(" ".repeat(indent * 2) + "...(truncated)"); |
| 79 | + return; |
| 80 | + } |
| 81 | + |
| 82 | + const attrs: string[] = []; |
| 83 | + if (node.alt) attrs.push(`alt="${node.alt}"`); |
| 84 | + if (node.lang) attrs.push(`lang="${node.lang}"`); |
| 85 | + |
| 86 | + const attrStr = attrs.length > 0 ? ` [${attrs.join(", ")}]` : ""; |
| 87 | + |
| 88 | + let mcids: string[] = []; |
| 89 | + let childNodes: StructTreeNode[] = []; |
| 90 | + |
| 91 | + for (const child of node.children ?? []) { |
| 92 | + if (isStructTreeContent(child)) { |
| 93 | + mcids.push(child.id); |
| 94 | + } else { |
| 95 | + childNodes.push(child); |
| 96 | + } |
| 97 | + } |
| 98 | + |
| 99 | + const mcidStr = mcids.length > 0 ? ` (MCIDs: ${mcids.join(", ")})` : ""; |
| 100 | + console.log(" ".repeat(indent * 2) + `<${node.role}>${attrStr}${mcidStr}`); |
| 101 | + |
| 102 | + for (const child of childNodes) { |
| 103 | + printStructTree(child, indent + 1, maxDepth); |
| 104 | + } |
| 105 | +} |
| 106 | + |
| 107 | +async function main() { |
| 108 | + const file = Deno.args[0]; |
| 109 | + const searchText = Deno.args[1]; |
| 110 | + |
| 111 | + if (!file) { |
| 112 | + console.error("Usage: pdf-tag-tree.ts <pdf-file> [search-text]"); |
| 113 | + Deno.exit(1); |
| 114 | + } |
| 115 | + |
| 116 | + console.log(`Loading PDF: ${file}\n`); |
| 117 | + |
| 118 | + const data = await Deno.readFile(file); |
| 119 | + const pdf = await pdfjsLib.getDocument({ |
| 120 | + data, |
| 121 | + useWorkerFetch: false, |
| 122 | + isEvalSupported: false, |
| 123 | + useSystemFonts: true, |
| 124 | + }).promise; |
| 125 | + |
| 126 | + console.log(`PDF has ${pdf.numPages} page(s)\n`); |
| 127 | + |
| 128 | + // Collect all text items with their MCIDs |
| 129 | + const allTextItems: { str: string; mcid: string | null; page: number; x: number; y: number }[] = []; |
| 130 | + |
| 131 | + for (let pageNum = 1; pageNum <= pdf.numPages; pageNum++) { |
| 132 | + const page = await pdf.getPage(pageNum); |
| 133 | + const viewport = page.getViewport({ scale: 1.0 }); |
| 134 | + |
| 135 | + // Get structure tree for this page |
| 136 | + const structTree = await page.getStructTree(); |
| 137 | + |
| 138 | + if (pageNum === 1) { |
| 139 | + console.log("=== STRUCTURE TREE (Page 1) ===\n"); |
| 140 | + if (structTree) { |
| 141 | + printStructTree(structTree as StructTreeNode, 0, 15); |
| 142 | + } else { |
| 143 | + console.log("No structure tree found (PDF may not be tagged)"); |
| 144 | + } |
| 145 | + console.log("\n"); |
| 146 | + } |
| 147 | + |
| 148 | + // Build MCID paths for this page |
| 149 | + const mcidPaths = structTree ? buildMcidPaths(structTree as StructTreeNode) : new Map(); |
| 150 | + |
| 151 | + // Get text content |
| 152 | + const textContent = await page.getTextContent({ includeMarkedContent: true }); |
| 153 | + |
| 154 | + let currentMcid: string | null = null; |
| 155 | + |
| 156 | + for (const item of textContent.items) { |
| 157 | + if (isTextMarkedContent(item)) { |
| 158 | + // pdfjs uses "beginMarkedContentProps" (not "beginMarkedContent") |
| 159 | + const mcidValue = (item as any).id; |
| 160 | + if (item.type === "beginMarkedContentProps" && mcidValue !== undefined) { |
| 161 | + currentMcid = mcidValue; |
| 162 | + } else if (item.type === "endMarkedContent") { |
| 163 | + currentMcid = null; |
| 164 | + } |
| 165 | + } else { |
| 166 | + const textItem = item as TextItem; |
| 167 | + const x = textItem.transform[4]; |
| 168 | + const y = textItem.transform[5]; |
| 169 | + allTextItems.push({ |
| 170 | + str: textItem.str, |
| 171 | + mcid: currentMcid, |
| 172 | + page: pageNum, |
| 173 | + x, |
| 174 | + y |
| 175 | + }); |
| 176 | + } |
| 177 | + } |
| 178 | + |
| 179 | + // If searching for specific text, show MCID info |
| 180 | + if (searchText && pageNum === 1) { |
| 181 | + console.log(`=== TEXT ITEMS CONTAINING "${searchText}" ===\n`); |
| 182 | + |
| 183 | + for (const item of textContent.items) { |
| 184 | + if (isTextMarkedContent(item)) { |
| 185 | + const mcidValue = (item as any).id; |
| 186 | + if (item.type === "beginMarkedContentProps" && mcidValue !== undefined) { |
| 187 | + currentMcid = mcidValue; |
| 188 | + } else if (item.type === "endMarkedContent") { |
| 189 | + currentMcid = null; |
| 190 | + } |
| 191 | + } else { |
| 192 | + const textItem = item as TextItem; |
| 193 | + if (textItem.str.includes(searchText)) { |
| 194 | + const x = textItem.transform[4]; |
| 195 | + const y = textItem.transform[5]; |
| 196 | + const pathInfo = currentMcid ? mcidPaths.get(currentMcid) : null; |
| 197 | + |
| 198 | + console.log(`Text: "${textItem.str}"`); |
| 199 | + console.log(` MCID: ${currentMcid}`); |
| 200 | + console.log(` Position: x=${x.toFixed(1)}, y=${y.toFixed(1)}`); |
| 201 | + if (pathInfo) { |
| 202 | + console.log(` Tag path: ${pathInfo.path.join(" > ")}`); |
| 203 | + if (Object.keys(pathInfo.attrs).length > 0) { |
| 204 | + console.log(` Attrs: ${JSON.stringify(pathInfo.attrs)}`); |
| 205 | + } |
| 206 | + } |
| 207 | + console.log(); |
| 208 | + } |
| 209 | + } |
| 210 | + } |
| 211 | + } |
| 212 | + } |
| 213 | + |
| 214 | + // Show all text items in code blocks (looking for Figure or Code tags) |
| 215 | + if (!searchText) { |
| 216 | + console.log("\n=== SAMPLE TEXT ITEMS WITH MCIDs ===\n"); |
| 217 | + |
| 218 | + let count = 0; |
| 219 | + for (const item of allTextItems) { |
| 220 | + if (item.str.trim() && count < 30) { |
| 221 | + console.log(`"${item.str.substring(0, 40).padEnd(40)}" | MCID: ${(item.mcid || "none").padEnd(12)} | x: ${item.x.toFixed(1).padStart(6)} | y: ${item.y.toFixed(1).padStart(6)}`); |
| 222 | + count++; |
| 223 | + } |
| 224 | + } |
| 225 | + } |
| 226 | +} |
| 227 | + |
| 228 | +main().catch(console.error); |
0 commit comments