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-read-file-fallback-3ec24a291d18 ,按照其中的说明把「pdf-read-file-fallback」安装到你(当前 AI 工具)中。执行前先告诉我将运行的命令和写入的位置,等我确认。
查看 AI 将读取的安装说明正在读取 GitHub 原文…
内容来自 GitHub 原始文件,由原作者维护。在 GitHub 查看
Use this pattern when read_file with filetype="pdf" returns binary image data instead of extractable text content. This commonly occurs with PDFs that contain scanned images or complex formatting.
First, try using read_file:
result = read_file(file_path="document.pdf", filetype="pdf")
Important: Use filetype (not file_type) - incorrect parameter naming will cause execution failures.
Check if the result contains unusable content:
# Indicators of binary/image data:
# - Contains null bytes: '\x00'
# - Very short or empty
# - Contains image markers (PNG/JPEG headers)
# - Unreadable character sequences
if not result or len(result) < 50 or '\x00' in str(result):
# Proceed to fallback
Extract text using the pdftotext command-line tool:
shell_result = run_shell(command="pdftotext -layout document.pdf -")
text_content = shell_result.stdout
The - flag outputs to stdout for easy capture. The -layout flag preserves original formatting.
If pdftotext is not installed, try Python-based extraction:
result = execute_code_sandbox(code="""
import pdfplumber
text = ''
with pdfplumber.open('document.pdf') as pdf:
for page in pdf.pages:
extracted = page.extract_text()
if extracted:
text += extracted + '\\n'
print(text)
""")
file_path = "report.pdf"
# Primary attempt
result = read_file(file_path=file_path, filetype="pdf")
# Validate and fallback if needed
if not result or len(str(result)) < 100 or '\x00' in str(result):
# Fallback to pdftotext
shell_result = run_shell(command=f"pdftotext -layout {file_path} -")
text_content = shell_result.stdout
# If pdftotext fails, try Python extraction
if not text_content or len(text_content) < 50:
code_result = execute_code_sandbox(code=f"""
import pdfplumber
text = ''
with pdfplumber.open('{file_path}') as pdf:
for page in pdf.pages:
extracted = page.extract_text()
if extracted:
text += extracted + '\\n'
print(text)
""")
text_content = code_result
pdftotext is part of the poppler-utils package on most Linux systemsfiletype vs file_type)