Extract text from PDF files using pdftotext when read_file returns binary data
复制下面这句话,粘贴给 Claude Code、Codex、Cursor 等 AI 编程工具,它会读取安装说明并在你确认后完成安装。
请阅读 https://ai.atlankj.com/install/asset/gh-pdf-text-extraction-9424c5-86b0ff1a9801 ,按照其中的说明把「pdf-text-extraction-9424c5」安装到你(当前 AI 工具)中。执行前先告诉我将运行的命令和写入的位置,等我确认。
查看 AI 将读取的安装说明正在读取 GitHub 原文…
内容来自 GitHub 原始文件,由原作者维护。在 GitHub 查看
When using read_file on PDF documents, the function may return binary image data or garbled content instead of readable text. This occurs because PDFs can contain scanned images or complex binary structures that read_file cannot properly parse as text.
Use the pdftotext command-line utility via run_shell to extract clean text content from PDF files.
import os
pdf_path = "path/to/document.pdf"
if not os.path.exists(pdf_path):
raise FileNotFoundError(f"PDF not found: {pdf_path}")
from tools import run_shell
# Extract text to stdout
result = run_shell(command=f"pdftotext '{pdf_path}' -", timeout=60)
pdf_text = result.stdout
# Alternative: extract to a temporary file
temp_txt = "/tmp/extracted.txt"
run_shell(command=f"pdftotext '{pdf_path}' '{temp_txt}'", timeout=60)
with open(temp_txt, 'r') as f:
pdf_text = f.read()
When calling read_file, be aware of the parameter name:
filetype="pdf" (not file_type)# Correct parameter usage
content = read_file(file_path="doc.pdf", filetype="pdf")
# If this returns binary/garbled data, fall back to pdftotext
| Option | Description |
|---|---|
- | Output to stdout |
-layout | Maintain original layout |
-f <n> | Start from page n |
-l <n> | End at page n |
-q | Quiet mode |
Example with options:
result = run_shell(command=f"pdftotext -layout -q '{pdf_path}' -", timeout=60)
from tools import run_shell
def extract_pdf_text(pdf_path):
"""Extract text from PDF using pdftotext with error handling."""
import os
if not os.path.exists(pdf_path):
raise FileNotFoundError(f"PDF not found: {pdf_path}")
result = run_shell(command=f"pdftotext '{pdf_path}' -", timeout=60)
if result.returncode != 0:
raise RuntimeError(f"pdftotext failed: {result.stderr}")
return result.stdout.strip()
read_file returns binary data, garbled text, or image content for a PDFpdftotext must be installed (part of poppler-utils on Debian/Ubuntu, poppler on macOS via Homebrew)run_shell(command="which pdftotext")