Skip to content

Commit cf821c6

Browse files
claude: Improve pdf-tag-tree to search all pages and highlight matches
- Make search-text required; determines which page's structure tree to show - Search all pages to find the text, not just page 1 - Exit with error if search text not found in PDF - Add "# <-- found" marker in structure tree for nodes containing matches - Update usage comment to show quarto run instead of deno run Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
1 parent a1f1f6a commit cf821c6

1 file changed

Lines changed: 92 additions & 89 deletions

File tree

‎tools/pdf-tag-tree.ts‎

Lines changed: 92 additions & 89 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,9 @@
55
* Extracts and displays the PDF structure tree (tag hierarchy) with MCIDs.
66
* Useful for debugging ensurePdfTextPositions issues.
77
*
8-
* Usage: deno run --allow-read --allow-env tools/pdf-tag-tree.ts <pdf-file> [search-text]
8+
* Usage: quarto run tools/pdf-tag-tree.ts <pdf-file> <search-text>
9+
*
10+
* The search-text is required and determines which page's structure tree to display.
911
*/
1012

1113
import * as pdfjsLib from "npm:pdfjs-dist@4.4.168/legacy/build/pdf.mjs";
@@ -73,7 +75,12 @@ function buildMcidPaths(
7375
}
7476

7577
// Pretty print the structure tree
76-
function printStructTree(node: StructTreeNode, indent: number = 0, maxDepth: number = 10): void {
78+
function printStructTree(
79+
node: StructTreeNode,
80+
indent: number = 0,
81+
maxDepth: number = 10,
82+
highlightMcids: Set<string> = new Set()
83+
): void {
7784
if (indent > maxDepth) {
7885
console.log(" ".repeat(indent * 2) + "...(truncated)");
7986
return;
@@ -97,24 +104,24 @@ function printStructTree(node: StructTreeNode, indent: number = 0, maxDepth: num
97104
}
98105

99106
const mcidStr = mcids.length > 0 ? ` (MCIDs: ${mcids.join(", ")})` : "";
100-
console.log(" ".repeat(indent * 2) + `<${node.role}>${attrStr}${mcidStr}`);
107+
const hasMatch = mcids.some(id => highlightMcids.has(id));
108+
const matchMarker = hasMatch ? " # <-- found" : "";
109+
console.log(" ".repeat(indent * 2) + `<${node.role}>${attrStr}${mcidStr}${matchMarker}`);
101110

102111
for (const child of childNodes) {
103-
printStructTree(child, indent + 1, maxDepth);
112+
printStructTree(child, indent + 1, maxDepth, highlightMcids);
104113
}
105114
}
106115

107116
async function main() {
108117
const file = Deno.args[0];
109118
const searchText = Deno.args[1];
110119

111-
if (!file) {
112-
console.error("Usage: pdf-tag-tree.ts <pdf-file> [search-text]");
120+
if (!file || !searchText) {
121+
console.error("Usage: quarto run tools/pdf-tag-tree.ts <pdf-file> <search-text>");
113122
Deno.exit(1);
114123
}
115124

116-
console.log(`Loading PDF: ${file}\n`);
117-
118125
const data = await Deno.readFile(file);
119126
const pdf = await pdfjsLib.getDocument({
120127
data,
@@ -123,103 +130,99 @@ async function main() {
123130
useSystemFonts: true,
124131
}).promise;
125132

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 }[] = [];
133+
// First pass: find which page contains the search text
134+
let foundPage: number | null = null;
130135

131136
for (let pageNum = 1; pageNum <= pdf.numPages; pageNum++) {
132137
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();
138+
const textContent = await page.getTextContent({ includeMarkedContent: true });
137139

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)");
140+
for (const item of textContent.items) {
141+
if (!isTextMarkedContent(item)) {
142+
const textItem = item as TextItem;
143+
if (textItem.str.includes(searchText)) {
144+
foundPage = pageNum;
145+
break;
146+
}
144147
}
145-
console.log("\n");
146148
}
149+
if (foundPage) break;
150+
}
147151

148-
// Build MCID paths for this page
149-
const mcidPaths = structTree ? buildMcidPaths(structTree as StructTreeNode) : new Map();
152+
if (!foundPage) {
153+
console.error(`Error: "${searchText}" not found in PDF`);
154+
Deno.exit(1);
155+
}
150156

151-
// Get text content
152-
const textContent = await page.getTextContent({ includeMarkedContent: true });
157+
console.log(`Found "${searchText}" on page ${foundPage}\n`);
153158

154-
let currentMcid: string | null = null;
159+
// Get the page with the search text
160+
const page = await pdf.getPage(foundPage);
161+
const structTree = await page.getStructTree();
155162

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-
}
163+
// Build MCID paths for this page
164+
const mcidPaths = structTree ? buildMcidPaths(structTree as StructTreeNode) : new Map();
178165

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-
}
166+
// Get text content and find MCIDs containing the search text
167+
const textContent = await page.getTextContent({ includeMarkedContent: true });
168+
169+
// First pass: collect MCIDs that contain the search text
170+
const matchingMcids = new Set<string>();
171+
let currentMcid: string | null = null;
172+
173+
for (const item of textContent.items) {
174+
if (isTextMarkedContent(item)) {
175+
const mcidValue = (item as any).id;
176+
if (item.type === "beginMarkedContentProps" && mcidValue !== undefined) {
177+
currentMcid = mcidValue;
178+
} else if (item.type === "endMarkedContent") {
179+
currentMcid = null;
180+
}
181+
} else {
182+
const textItem = item as TextItem;
183+
if (textItem.str.includes(searchText) && currentMcid !== null) {
184+
matchingMcids.add(currentMcid);
210185
}
211186
}
212187
}
213188

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");
189+
console.log(`=== STRUCTURE TREE (Page ${foundPage}) ===\n`);
190+
if (structTree) {
191+
printStructTree(structTree as StructTreeNode, 0, 15, matchingMcids);
192+
} else {
193+
console.log("No structure tree found (PDF may not be tagged)");
194+
}
195+
console.log("\n");
196+
197+
console.log(`=== TEXT ITEMS CONTAINING "${searchText}" ===\n`);
198+
199+
currentMcid = null;
217200

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++;
201+
for (const item of textContent.items) {
202+
if (isTextMarkedContent(item)) {
203+
const mcidValue = (item as any).id;
204+
if (item.type === "beginMarkedContentProps" && mcidValue !== undefined) {
205+
currentMcid = mcidValue;
206+
} else if (item.type === "endMarkedContent") {
207+
currentMcid = null;
208+
}
209+
} else {
210+
const textItem = item as TextItem;
211+
if (textItem.str.includes(searchText)) {
212+
const x = textItem.transform[4];
213+
const y = textItem.transform[5];
214+
const pathInfo = currentMcid ? mcidPaths.get(currentMcid) : null;
215+
216+
console.log(`Text: "${textItem.str}"`);
217+
console.log(` MCID: ${currentMcid}`);
218+
console.log(` Position: x=${x.toFixed(1)}, y=${y.toFixed(1)}`);
219+
if (pathInfo) {
220+
console.log(` Tag path: ${pathInfo.path.join(" > ")}`);
221+
if (Object.keys(pathInfo.attrs).length > 0) {
222+
console.log(` Attrs: ${JSON.stringify(pathInfo.attrs)}`);
223+
}
224+
}
225+
console.log();
223226
}
224227
}
225228
}

0 commit comments

Comments
 (0)