Extract text from PDFs using pdftotext when read_file returns binary data
复制下面这句话,粘贴给 Claude Code、Codex、Cursor 等 AI 编程工具,它会读取安装说明并在你确认后完成安装。
请阅读 https://ai.atlankj.com/install/asset/gh-pdf-text-extraction-fallback-2156afef8cfa ,按照其中的说明把「pdf-text-extraction-fallback」安装到你(当前 AI 工具)中。执行前先告诉我将运行的命令和写入的位置,等我确认。
查看 AI 将读取的安装说明正在读取 GitHub 原文…
内容来自 GitHub 原始文件,由原作者维护。在 GitHub 查看
Use this skill when read_file with filetype="pdf" returns binary/image data instead of readable text content. This is a common issue with PDF files that contain embedded images or complex formatting.
Before attempting extraction, ensure you're using the correct parameter name:
filetype (not file_type) for the read_file function# Correct
read_file(filetype="pdf", file_path="document.pdf")
# Incorrect - may fail silently
read_file(file_type="pdf", file_path="document.pdf")
After calling read_file, check if the result contains:
b'...' byte strings with non-text content)If yes, proceed with the pdftotext workaround.
Use run_shell to call pdftotext, which extracts text directly from PDF files:
# Extract text to stdout
result = run_shell(command="pdftotext /path/to/document.pdf -")
text_content = result.stdout
The - flag tells pdftotext to output to stdout instead of creating a file.
result = run_shell(command="pdftotext /path/to/document.pdf -")
if result.stderr:
# Check for errors like "pdftotext not found"
# May need to install poppler-utils
pass
text_content = result.stdout
# text_content now contains the extracted text
# Step 1: Try normal read with correct parameters
content = read_file(filetype="pdf", file_path="reference.pdf")
# Step 2: Check if content is readable
if not content or looks_like_binary(content):
# Step 3: Fall back to pdftotext
result = run_shell(command="pdftotext reference.pdf -")
text_content = result.stdout
# Step 4: Verify extraction succeeded
if result.stderr:
# Handle error (e.g., install pdftotext)
pass
pdftotext is part of the poppler-utils package:
apt-get install poppler-utilsbrew install popplerIf stdout approach has issues, output to a temporary file:
run_shell(command="pdftotext /path/to/document.pdf /tmp/output.txt")
text_content = read_file(filetype="txt", file_path="/tmp/output.txt")
filetype parameter spelling before troubleshooting