pdf-extraction-fallback
What it does
This skill is a ladder of PDF and document extraction methods, from Python libraries to command line tools. It is for people whose document reading fails on the first try.
When to use it
- ✓When a document reading tool fails on a PDF that must be read.
- ✓When the document is encrypted or has formatting that stops the first method.
- ✓When I want the AI to keep going through options instead of stopping after one error.
Skill link
https://github.com/HKUDS/AgentPilot/blob/main/openspace/benchmarks/gdpval/skills/pdf-extraction-fallback/SKILL.mdCopy it and paste it into your AI (Claude, ChatGPT or Cursor), asking it to follow the instructions.
How to use
The easiest way: copy the message and paste it into your AI. It reads the skill and follows the instructions.
Ready-to-paste message
For Claude Code, Codex or Cursor: run it in your project folder and the skill gets installed.
Download the SKILL.md and drop it into your agent’s skills folder.
Example of what to ask your AI
“The first tool could not read my PDF. Please keep trying the other methods until you have the text.”
5 new skills a week. 1 minute to read.
How it works
The AI tries a Python PDF library first, then falls back to pdftotext from the shell, and continues down the list of methods until the text is extracted.
Technical content (original SKILL.md)
Original text by the author, straight from GitHub.
PDF Extraction Fallback Strategy
When processing documents (especially PDFs), initial extraction attempts may fail due to formatting, encryption, or tool limitations. This skill provides a systematic fallback approach that tries multiple extraction methods before declaring failure.
Core Principle
Never declare completion after a single tool failure. Instead, iterate through a hierarchy of extraction methods, each with different capabilities and limitations.
Fallback Hierarchy
Attempt extraction methods in this order:
Stage 1: Direct PDF Reading
Try native PDF libraries first (fastest, preserves structure):
import PyPDF2
from pypdf import PdfReader
def extract_with_pypdf(pdf_path):
reader = PdfReader(pdf_path)
text = ""
for page in reader.pages:
text += page.extract_text() or ""
return text
Stage 2: Shell-based Extraction (pdftotext)
If Stage 1 fails, use system tools:
# Install if needed: apt-get install poppler-utils
pdftotext -layout input.pdf output.txt
pdftotext -raw input.pdf output.txt # Alternative layout
import subprocess
def extract_with_pdftotext(pdf_path):
result = subprocess.run(
['pdftotext', '-layout', pdf_path, '-'],
capture_output=True, text=True
)
if result.returncode == 0:
return result.stdout
raise Exception("pdftotext failed")
Stage 3: Alternative Python Parsers
Try different Python libraries with varying capabilities:
# pdfplumber - better for tables
import pdfplumber
def extract_with_pdfplumber(pdf_path):
text = ""
with pdfplumber.open(pdf_path) as pdf:
for page in pdf.pages:
text += page.extract_text() or ""
return text
# pdfminer - handles complex layouts
from pdfminer.high_level import extract_text
def extract_with_pdfminer(pdf_path):
return extract_text(pdf_path)
Stage 4: OCR Fallback
For scanned images or when text extraction fails:
# Using tesseract
convert input.pdf output-%d.png # Convert to images first
tesseract output-0.png result --psm 6
# Using pytesseract
from pdf2image import convert_from_path
import pytesseract
def extract_with_ocr(pdf_path):
images = convert_from_path(pdf_path, dpi=300)
text = ""
for image in images:
text += pytesseract.image_to_string(image)
return text
Implementation Pattern
def robust_pdf_extraction(pdf_path):
"""Try multiple extraction methods until one succeeds."""
extraction_methods = [
("PyPDF2", extract_with_pypdf),
("pdftotext", extract_with_pdftotext),
("pdfplumber", extract_with_pdfplumber),
("pdfminer", extract_with_pdfminer),
("OCR", extract_with_ocr),
]
errors = []
for method_name, method_func in extraction_methods:
try:
print(f"Trying {method_name}...")
text = method_func(pdf_path)
if text and text.strip():
print(f"Success with {method_name}")
return text
else:
errors.append(f"{method_name}: empty result")
except Exception as e:
errors.append(f"{method_name}: {str(e)}")
print(f"{method_name} failed: {e}")
continue
# All methods failed
raise Exception(f"All extraction methods failed:\n" + "\n".join(errors))
Success Criteria
A method is considered successful when:
- No exceptions are raised during execution
- Non-empty text is returned (text.strip() has content)
- Content quality meets task requirements (check for expected keywords/patterns)
Best Practices
- Log each attempt - Record which methods were tried and why they failed
- Validate output - Check extracted text contains expected content markers
- Graceful degradation - Proceed with partial data if full extraction isn't possible
- Cache successful method - Remember which method worked for similar files
- Set timeouts - Prevent OCR or complex parsing from hanging indefinitely
Common Failure Modes
| Symptom | Likely Cause | Best Fallback |
|---|---|---|
| Empty pages | Image-based PDF | OCR (Stage 4) |
| Garbled text | Encoding issues | pdftotext (Stage 2) |
| Missing tables | Simple parser | pdfplumber (Stage 3) |
| Permission errors | Encrypted PDF | Check password/permissions first |
| Layout lost | Complex formatting |
FAQ
Which method comes first?
The guide starts with a native Python PDF library, which keeps the structure well.
Why use pdftotext next?
It is a system tool that works when the Python library fails.
Should the AI stop after one failure?
No, the guide says never to declare completion after a single tool failure.
Details
Original description by the author
Multi-stage fallback strategy for PDF/document extraction using sequential tool alternatives
repo: HKUDS/AgentPilot
Popularity
- GitHub stars
- 7.8k
- Ranking position
- #12923
- License
- MIT
- Updated
- 11/1/2026
Comments
- …
More skills from this repository
agentpilot
7.8kHelps your agent improve a project step by step by preparing a task and running the AgentPilot loop that proposes, tests and scores changes.
openspace
7.8kHelps your agent set up OpenSpace, a tool that stores and fetches agent skills, and connect it to your AI app through MCP.
rsi-arena
7.8kHelps your agent set up and run standard AI benchmark tests, such as AIME and Terminal-Bench, to compare different improvement methods.
experiment-guide
7.8kHelps your agent plan small experiments, read their results and record findings while it investigates how to improve a program.
Similar skills
feishu-doc
394kHelps your agent read, create, and edit Feishu cloud documents, including text, images, and tables, using the document tool.
feishu-drive
394kLets your agent browse, organize, and comment on files in a Feishu cloud folder that has been shared with the bot.
feishu-perm
394kHelps your agent check and change who can access a Feishu file, choosing the smallest permission that meets your request.