get_pdf_text
Extract text from specific pages or page ranges of a PDF file using native text extraction. Supports Python-style slicing and both absolute and relative paths.
Instructions
Extract text from specific pages or page ranges of a PDF file using native text extraction. Supports Python-style slicing: '5' (single page), '5:10' (range), '7:' (from page 7 to end), ':5' (from start to page 5). Use either absolute_path for any location or relative_path for files in ~/pdf-agent/ directory. Note: Works best with PDFs containing native text; scanned PDFs may yield limited results.
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| absolute_path | No | Absolute path to the PDF file (e.g., '/Users/john/documents/report.pdf') | |
| relative_path | No | Path relative to ~/pdf-agent/ directory (e.g., 'reports/annual.pdf') | |
| use_pdf_home | No | Use PDF agent home directory for relative paths (default: true) | |
| page_range | No | Page range in enhanced Python-style format: '5' (page 5), '5:10' (pages 5-10), '7:' (page 7 to end), ':5' (start to page 5). Also supports comma-separated combinations: '1,3:5,7' (pages 1, 3-5, and 7), '1-3,7,10:' (pages 1-3, 7, and 10 to end). Default: '1:' (all pages) | 1: |
| extraction_strategy | No | Text extraction strategy: 'hybrid' (enhanced native extraction with better error handling), 'native' (standard PDF.js extraction). Default: 'hybrid' | hybrid |
| preserve_formatting | No | Preserve text formatting and spacing (default: true) | |
| line_breaks | No | Preserve line breaks in extracted text (default: true) |
Implementation Reference
- src/index.ts:112-125 (schema)Zod schema defining the input validation for get_pdf_text tool. Validates absolute_path/relative_path (exactly one required), page_range, extraction_strategy, preserve_formatting, and line_breaks parameters.
const GetPdfTextSchema = z.object({ absolute_path: z.string().optional(), relative_path: z.string().optional(), use_pdf_home: z.boolean().default(true), page_range: z.string().default("1:"), extraction_strategy: z.enum(["hybrid", "native"]).default("hybrid"), preserve_formatting: z.boolean().default(true), line_breaks: z.boolean().default(true), }).refine( (data) => (data.absolute_path && !data.relative_path) || (!data.absolute_path && data.relative_path), { message: "Exactly one of 'absolute_path' or 'relative_path' must be provided", } ); - src/index.ts:1479-1521 (registration)Tool registration in the ListToolsRequestSchema handler. Defines the tool name 'get_pdf_text', its description, and inputSchema for MCP protocol.
{ name: "get_pdf_text", description: "Extract text from specific pages or page ranges of a PDF file using native text extraction. Supports Python-style slicing: '5' (single page), '5:10' (range), '7:' (from page 7 to end), ':5' (from start to page 5). Use either absolute_path for any location or relative_path for files in ~/pdf-agent/ directory. Note: Works best with PDFs containing native text; scanned PDFs may yield limited results.", inputSchema: { type: "object", properties: { absolute_path: { type: "string", description: "Absolute path to the PDF file (e.g., '/Users/john/documents/report.pdf')", }, relative_path: { type: "string", description: "Path relative to ~/pdf-agent/ directory (e.g., 'reports/annual.pdf')", }, use_pdf_home: { type: "boolean", description: "Use PDF agent home directory for relative paths (default: true)", default: true, }, page_range: { type: "string", description: "Page range in enhanced Python-style format: '5' (page 5), '5:10' (pages 5-10), '7:' (page 7 to end), ':5' (start to page 5). Also supports comma-separated combinations: '1,3:5,7' (pages 1, 3-5, and 7), '1-3,7,10:' (pages 1-3, 7, and 10 to end). Default: '1:' (all pages)", default: "1:", }, extraction_strategy: { type: "string", description: "Text extraction strategy: 'hybrid' (enhanced native extraction with better error handling), 'native' (standard PDF.js extraction). Default: 'hybrid'", enum: ["hybrid", "native"], default: "hybrid", }, preserve_formatting: { type: "boolean", description: "Preserve text formatting and spacing (default: true)", default: true, }, line_breaks: { type: "boolean", description: "Preserve line breaks in extracted text (default: true)", default: true, }, }, }, }, - src/index.ts:1911-2053 (handler)Main handler for the get_pdf_text tool in CallToolRequestSchema. Resolves the file path, reads the PDF, parses page range, extracts text using either 'native' (extractTextNative) or 'hybrid' (extractTextHybrid) strategy, and returns formatted results with word/character counts per page.
case "get_pdf_text": { const { absolute_path, relative_path, use_pdf_home, page_range, extraction_strategy, preserve_formatting, line_breaks } = GetPdfTextSchema.parse(args); try { // Resolve the final path based on parameters (same logic as metadata tool) let resolvedPath: string; if (use_pdf_home && relative_path) { // Use relative path from PDF agent home directory const pdfAgentHome = await ensurePdfAgentHome(); resolvedPath = join(pdfAgentHome, relative_path); } else if (absolute_path) { // Use absolute path directly if (!isAbsolute(absolute_path)) { return { content: [ { type: "text", text: JSON.stringify({ error: `Path '${absolute_path}' is not absolute. Use relative_path parameter for relative paths or provide a full absolute path.` }), }, ], }; } resolvedPath = absolute_path; } else { return { content: [ { type: "text", text: JSON.stringify({ error: `Must provide either 'absolute_path' or 'relative_path'. Examples: {"absolute_path": "/Users/john/document.pdf"} or {"relative_path": "reports/annual.pdf"}` }), }, ], }; } if (!(await fileExists(resolvedPath))) { const pathType = relative_path ? 'relative path' : 'absolute path'; const homeInfo = relative_path ? ` (resolved from ~/pdf-agent/ to ${resolvedPath})` : ''; return { content: [ { type: "text", text: JSON.stringify({ error: `PDF file not found at ${pathType}: ${relative_path || absolute_path}${homeInfo}. Please check the file path and ensure the file exists.` }), }, ], }; } // Read the PDF file const pdfBuffer = await safeReadFile(resolvedPath); // Get PDF document to determine total pages let pdfDoc: PDFDocument; try { pdfDoc = await PDFDocument.load(pdfBuffer); } catch (error) { if (error instanceof Error && error.message.includes('encrypted')) { pdfDoc = await PDFDocument.load(pdfBuffer, { ignoreEncryption: true }); } else { throw error; } } const totalPages = pdfDoc.getPageCount(); // Parse page range const pageNumbers = parsePageRange(page_range, totalPages); log('info', `Extracting text from ${pageNumbers.length} pages using ${extraction_strategy} strategy`, { pages: pageNumbers, strategy: extraction_strategy }); // Extract text based on strategy let extractedTexts: string[]; switch (extraction_strategy) { case "native": extractedTexts = await extractTextNative(pdfBuffer, pageNumbers); break; case "hybrid": default: extractedTexts = await extractTextHybrid(pdfBuffer, resolvedPath, pageNumbers); break; } // Format the results const results = pageNumbers.map((pageNum, index) => ({ page: pageNum, text: extractedTexts[index] || '', word_count: (extractedTexts[index] || '').split(/\s+/).filter(word => word.length > 0).length, char_count: (extractedTexts[index] || '').length })); return { content: [ { type: "text", text: JSON.stringify({ file_path: resolvedPath, total_pages: totalPages, extracted_pages: pageNumbers.length, page_range: page_range, extraction_strategy: extraction_strategy, results: results, summary: { total_text_length: results.reduce((sum, r) => sum + r.char_count, 0), total_word_count: results.reduce((sum, r) => sum + r.word_count, 0), pages_with_text: results.filter(r => r.text.trim().length > 0).length } }), }, ], }; } catch (e) { const providedPath = relative_path || absolute_path || 'unknown'; const pathType = relative_path ? 'relative path' : 'absolute path'; return { content: [ { type: "text", text: JSON.stringify({ error: `Error extracting text from PDF at ${pathType} '${providedPath}': ${e}. Please ensure the file is a valid PDF and check the page range format.` }), }, ], }; } } - src/index.ts:396-456 (helper)Core text extraction helper using native PDF.js. Suppresses console output during PDF operations, iterates through requested pages, extracts text items with spacing detection (inserts spaces for gaps on same line, newlines for next line), and returns array of page texts.
async function extractTextNative(pdfBuffer: Buffer, pageNumbers: number[]): Promise<string[]> { let pdfDoc: any; // Suppress console output during PDF.js operations to prevent stdout contamination suppressConsoleOutput(); try { pdfDoc = await pdfjsLib.getDocument({ data: new Uint8Array(pdfBuffer) }).promise; } finally { restoreConsoleOutput(); } const texts: string[] = []; for (const pageNum of pageNumbers) { try { // Suppress console output for each page operation as well suppressConsoleOutput(); let page: any; let textContent: any; try { page = await pdfDoc.getPage(pageNum); textContent = await page.getTextContent(); } finally { restoreConsoleOutput(); } const textItems = textContent.items as any[]; // Combine text items with spacing let pageText = ''; for (let i = 0; i < textItems.length; i++) { const item = textItems[i]; if (item.str) { pageText += item.str; // Add space if next item is on same line but has gap if (i < textItems.length - 1) { const nextItem = textItems[i + 1]; if (nextItem.str && item.transform[5] === nextItem.transform[5]) { // Same line, check for gap const gap = nextItem.transform[4] - item.transform[4] - item.width; if (gap > 5) { pageText += ' '; } } else if (nextItem.str) { // Different line, add newline pageText += '\n'; } } } } texts.push(pageText.trim()); } catch (error) { log('warn', `Failed to extract text from page ${pageNum}`, { error }); texts.push(''); } } return texts; } - src/index.ts:461-491 (helper)Hybrid extraction helper that wraps extractTextNative with enhanced error handling. Provides warnings when pages yield very little text (potentially scanned content). Used by get_pdf_text handler when extraction_strategy is 'hybrid'.
*/ async function extractTextHybrid(pdfBuffer: Buffer, pdfPath: string, pageNumbers: number[]): Promise<string[]> { try { // Use native extraction with enhanced error handling const nativeTexts = await extractTextNative(pdfBuffer, pageNumbers); // Check if pages have very little text (likely scanned PDFs) const results: string[] = []; let scannedPageCount = 0; for (let i = 0; i < nativeTexts.length; i++) { const text = nativeTexts[i]; results.push(text); // Count pages with very little text if (text.trim().length < 50) { scannedPageCount++; } } // Log warning if many pages appear to be scanned if (scannedPageCount > 0) { log('warn', `${scannedPageCount} page(s) extracted very little text - may be scanned/image-based content`); } return results; } catch (error) { log('error', 'Text extraction failed', { error }); throw error; } }