Skip to content
Skillpedia
PDF, Word & slides7.8k Β· #12925

pdf-extraction-fallbacks

What it does

This skill is a multi-method workflow for reading PDFs, with validation before parsing. It is for people who need PDF text from sources that sometimes fail.

When to use it

  • βœ“When a PDF source may have been corrupted or replaced by an error page.
  • βœ“When extracting text from a PDF fails on the first method.
  • βœ“When I want a record of which method worked for future jobs.

Skill link

https://github.com/HKUDS/AgentPilot/blob/main/openspace/benchmarks/gdpval/skills/pdf-extraction-fallbacks/SKILL.md

Copy 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

Use this skill to help me: https://github.com/HKUDS/AgentPilot/blob/main/openspace/benchmarks/gdpval/skills/pdf-extraction-fallbacks/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
Want your AI to find skills like this on its own?Install the free Skillpedia MCP: one line, and it searches 15,000+ skills before each task.Install in 1 minute β†’

Example of what to ask your AI

β€œGet the text from this PDF link. Check that the download is valid, try several methods, and tell me which one worked.”

5 new skills a week. 1 minute to read.

How it works

The AI downloads the file, checks its size and PDF signature, then runs the extraction methods one after another and records the one that succeeded.

Technical content (original SKILL.md)

Original text by the author, straight from GitHub.

PDF Extraction with Multi-Fallback Strategy

Purpose

When extracting text from PDFs (especially regulatory documents, handbooks, or protected content), single-method approaches often fail due to JavaScript protection, CORS restrictions, encoding issues, or corrupted downloads. This skill provides a robust multi-fallback workflow that detects failures early and tries sequential extraction methods.

Core Pattern

  1. Download with validation - Check file size and content sanity immediately
  2. Sequential extraction attempts - Try multiple tools in order of reliability
  3. Early failure detection - Don't proceed with obviously corrupt files
  4. Document fallback path - Log which method succeeded for future reference

Step-by-Step Instructions

Step 1: Download and Validate

Before attempting extraction, validate the downloaded file:

# Download the PDF
curl -L -o document.pdf "$URL"

# Check file size (reject if < 1KB - likely error page)
FILE_SIZE=$(stat -f%z document.pdf 2>/dev/null || stat -c%s document.pdf 2>/dev/null)
if [ "$FILE_SIZE" -lt 1024 ]; then
    echo "ERROR: File too small ($FILE_SIZE bytes) - likely not a valid PDF"
    # Check if it's an HTML error page
    head -c 200 document.pdf | grep -i "<html\|<!doctype\|error\|access denied" && \
        echo "Detected HTML error page instead of PDF"
    exit 1
fi

# Check PDF magic bytes
HEAD_BYTES=$(head -c 4 document.pdf)
if [ "$HEAD_BYTES" != "%PDF" ]; then
    echo "ERROR: File does not start with PDF magic bytes"
    head -c 100 document.pdf
    exit 1
fi

Step 2: Primary Extraction (pdftotext)

# Try pdftotext first (fastest, most reliable for simple PDFs)
if command -v pdftotext &> /dev/null; then
    pdftotext -layout document.pdf output.txt 2>/dev/null
    if [ -s output.txt ]; then
        WORD_COUNT=$(wc -w < output.txt)
        if [ "$WORD_COUNT" -gt 50 ]; then
            echo "SUCCESS: pdftotext extracted $WORD_COUNT words"
            exit 0
        fi
    fi
fi

Step 3: Fallback 1 (PyMuPDF/fitz)

# Try PyMuPDF - handles more complex PDFs
import fitz  # pymupdf

try:
    doc = fitz.open("document.pdf")
    text = ""
    for page in doc:
        text += page.get_text()
    
    if len(text.strip()) > 500:  # Sanity check
        with open("output.txt", "w") as f:
            f.write(text)
        print(f"SUCCESS: PyMuPDF extracted {len(text)} characters")
    else:
        print("WARNING: PyMuPDF extraction too short, trying next method")
except Exception as e:
    print(f"PyMuPDF failed: {e}")

Step 4: Fallback 2 (pdfplumber)

# Try pdfplumber - better for tables and structured content
import pdfplumber

try:
    text = ""
    with pdfplumber.open("document.pdf") as pdf:
        for page in pdf.pages:
            page_text = page.extract_text()
            if page_text:
                text += page_text + "\n"
    
    if len(text.strip()) > 500:
        with open("output.txt", "w") as f:
            f.write(text)
        print(f"SUCCESS: pdfplumber extracted {len(text)} characters")
    else:
        print("WARNING: pdfplumber extraction too short")
except Exception as e:
    print(f"pdfplumber failed: {e}")

Step 5: Handle JavaScript-Protected Pages

If all methods fail, the PDF may be JavaScript-protected:

# Check for JavaScript in PDF
import fitz

doc = fitz.open("document.pdf")
has_js = False
for page in doc:
    if page.get_java_script():
        has_js = True
        break

if has_js:
    print("WARNING: PDF contains JavaScript - may be protected")
    # Try rendering pages as images and OCR (requires additional tools)
    # Or try alternative download source

Step 6: Alternative Sources

If the primary URL fails:

  • Try alternative domains (e.g., .gov mirrors, archive.org)
  • Check if the document is available via API
  • Look for HTML version of the same content
  • Search for the document title + "pdf" to find mirrors

Decision Tree

Download PDF
    β”‚
    β”œβ”€β†’ File < 1KB? β†’ REJECT (likely error page)
    β”œβ”€β†’ No %PDF header? β†’ REJECT (not a PDF)
    β”‚
    └─→ Valid PDF
         β”‚
         β”œβ”€β†’ pdftotext β†’ >50 words? β†’ SUCCESS
         β”‚              └─→ Try next
         β”‚
         β”œβ”€β†’ PyMuPDF β†’ >500 chars? β†’ SUCCESS
         β”‚             └─→ Try next
         β”‚
         β”œβ”€β†’ pdfplumber β†’ >500 chars? β†’ SUCCESS
         β”‚                 └─→ Try next
         β”‚
         └─→ All failed β†’ Check for JS protection, try alternat
FAQ

How is the file checked before parsing?

The guide checks the file size and whether the start of the file looks like a PDF rather than an HTML page.

Why record the successful method?

The guide says it helps later work use the method that already worked.

Can it skip a bad download?

Yes, the guide stops early when the file is clearly not a valid PDF.

Details

Original description by the author

Multi-fallback PDF/text extraction with early failure detection and sequential tool fallbacks

repo: HKUDS/AgentPilot

Popularity

GitHub stars
7.8k
Ranking position
#12925
License
MIT
Updated
11/1/2026

Is this skill useful?

0

Sign in to vote.

Comments

  • …

More skills from this repository

Similar skills