Recover PDF text extraction when read_file returns binary data by using pdftotext via shell
复制下面这句话,粘贴给 Claude Code、Codex、Cursor 等 AI 编程工具,它会读取安装说明并在你确认后完成安装。
请阅读 https://ai.atlankj.com/install/asset/gh-pdftotext-fallback-44d63dc10afd ,按照其中的说明把「pdftotext-fallback」安装到你(当前 AI 工具)中。执行前先告诉我将运行的命令和写入的位置,等我确认。
查看 AI 将读取的安装说明正在读取 GitHub 原文…
内容来自 GitHub 原始文件,由原作者维护。在 GitHub 查看
Apply this pattern when:
read_file on a PDF returns binary/image data instead of readable textexecute_code_sandbox fails or returns garbled contentThe pdftotext utility (from poppler-utils) is a mature, command-line tool that handles many PDF edge cases that confuse Python libraries or the read_file tool. It's pre-installed on most Linux systems and provides consistent, reliable text extraction.
Recognize extraction failure when:
read_file returns binary content, image data, or garbled textExtract to stdout (recommended for quick extraction):
pdftotext /path/to/file.pdf -
The - argument outputs directly to stdout for easy capture in your tool response.
Example:
run_shell("pdftotext document.pdf -")
Preserve layout (maintains original formatting):
pdftotext -layout /path/to/file.pdf -
Extract to a file (for large PDFs):
pdftotext /path/to/file.pdf /path/to/output.txt
Then read the output file with read_file.
Handle encoded text:
pdftotext -enc UTF-8 /path/to/file.pdf -
Basic extraction:
# Simple text extraction
text = run_shell("pdftotext document.pdf -")
With error handling:
# Try extraction, check for success
result = run_shell("pdftotext document.pdf - && echo 'SUCCESS' || echo 'FAILED'")
Multi-page PDF with layout:
# Preserve tables and formatting
text = run_shell("pdftotext -layout document.pdf -")
| Issue | Solution |
|---|---|
pdftotext: command not found | Install poppler-utils: apt-get install poppler-utils |
| Garbled/special characters | Try -enc UTF-8 or -enc ASCII7 |
| Missing formatting | Use -layout flag |
| Scanned PDF (no text) | Requires OCR (e.g., tesseract), not text extraction |
| Large PDF timeout | Extract to file instead of stdout |
pdfinfo: Get PDF metadata (pages, size, etc.)pdftoppm: Convert PDF pages to imagestesseract: OCR for scanned PDFs