Skip to main content
Glama

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

TableJSON Schema
NameRequiredDescriptionDefault
absolute_pathNoAbsolute path to the PDF file (e.g., '/Users/john/documents/report.pdf')
relative_pathNoPath relative to ~/pdf-agent/ directory (e.g., 'reports/annual.pdf')
use_pdf_homeNoUse PDF agent home directory for relative paths (default: true)
page_rangeNoPage 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_strategyNoText extraction strategy: 'hybrid' (enhanced native extraction with better error handling), 'native' (standard PDF.js extraction). Default: 'hybrid'hybrid
preserve_formattingNoPreserve text formatting and spacing (default: true)
line_breaksNoPreserve line breaks in extracted text (default: true)

Implementation Reference

  • 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,
          },
        },
      },
    },
  • 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.` 
              }),
            },
          ],
        };
      }
    }
  • 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;
    }
  • 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;
      }
    }
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, description fully carries behavioral disclosure. It details native extraction, Python-style slicing, default page range, and extraction strategy. It also notes the 'hybrid' strategy and preservation options, giving agents a clear understanding of behavior.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Concise, well-structured description: starts with purpose, then gives examples, usage notes, and limitations. Every sentence is informative with no redundancy. Front-loaded with core functionality.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Covers purpose, parameter usage, defaults, limitations, and extraction strategies. Minor gap: no description of output format (e.g., raw text concatenation), but overall sufficient given sibling tools and no output schema.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters5/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema coverage is 100%, baseline 3, but description adds significant value beyond schema: explicit Python slicing examples, clarification of absolute vs relative paths, explanation of extraction strategies, and defaults. This greatly aids agent in parameter selection.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

Description clearly states extraction of text from PDF pages using native text extraction. It specifies the resource (PDF file) and action (extract text), and supports page ranges, distinguishing it from siblings like get_pdf_images or get_pdf_metadata.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Provides explicit guidance on when to use (PDFs with native text) and limitations (scanned PDFs may yield limited results). It explains path options and slicing syntax, but does not explicitly compare to siblings like search_pdf for alternative use cases.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/vlad-ds/pdf-agent-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server