Home
cd ../playbooks
Data & ReportingBeginner

Table Extraction from Documents

Extract tables from PDF documents with support for merged cells and multi-page layouts using camelot.

10 minutes
By communitySource
#table#extraction#pdf#camelot

Financial reports, research papers, and government filings have tables locked inside PDFs that you need in a spreadsheet — but copy-paste destroys the formatting. This playbook extracts tables from PDFs using Camelot with support for merged cells, multi-page layouts, and complex table structures.

Who it's for: data analysts extracting tabular data from PDF financial reports and regulatory filings, researchers pulling data tables from published scientific papers for meta-analysis, finance teams converting PDF bank statements and invoices into spreadsheet format, operations managers extracting pricing and inventory tables from vendor PDF catalogs, compliance teams digitizing tabular data from scanned audit documents

Example

"Extract all tables from this 50-page annual report PDF" → Table extraction pipeline: PDF page analysis detecting table boundaries and structure, Camelot extraction handling merged cells and multi-column layouts, per-table quality validation checking row/column alignment, output as clean pandas DataFrames or CSV files, and batch processing for multi-page tables spanning across page breaks

CLAUDE.md Template

New here? 3-minute setup guide → | Already set up? Copy the template below.

Or install from your terminal:
npx ccplaybooks add table-extractor
# Table Extractor

## Overview

This workflow enables precise extraction of tables from PDF documents using **camelot** - the gold standard for PDF table extraction. Handle complex tables with merged cells, borderless tables, and multi-page layouts with high accuracy.

## How to Use

1. Provide the PDF containing tables
2. Optionally specify pages or table detection method
3. I'll extract tables as pandas DataFrames

Get new playbooks like this one

One email a week with new Claude Code workflows. Free, like everything here.

No spam. Unsubscribe anytime.

README.md

What This Does

This workflow enables precise extraction of tables from PDF documents using camelot - the gold standard for PDF table extraction. Handle complex tables with merged cells, borderless tables, and multi-page layouts with high accuracy.


Quick Start

Step 1: Create a Project Folder

mkdir -p ~/Documents/TableExtractor

Step 2: Download the Template

Click Download above, then:

mv ~/Downloads/CLAUDE.md ~/Documents/TableExtractor/

Step 3: Start Working

cd ~/Documents/TableExtractor
claude

How to Use

  1. Provide the PDF containing tables
  2. Optionally specify pages or table detection method
  3. I'll extract tables as pandas DataFrames

Example prompts:

  • "Extract all tables from this PDF"
  • "Get the table on page 5 of this report"
  • "Extract borderless tables from this document"
  • "Convert PDF tables to Excel format"

Best Practices

  1. Try Both Methods: Lattice for bordered, stream for borderless
  2. Check Accuracy Score: Above 90% is usually good
  3. Use Visual Debugging: Understand extraction results
  4. Specify Areas: For PDFs with multiple table types
  5. Handle Headers: First row often needs special treatment

Examples

Example 1: Financial Statement Extraction

import camelot
import pandas as pd

def extract_financial_tables(pdf_path):
    """Extract financial tables from annual report."""
    
    # Extract all tables
    tables = camelot.read_pdf(pdf_path, pages='all', flavor='lattice')
    
    financial_data = {
        'income_statement': None,
        'balance_sheet': None,
        'cash_flow': None,
        'other_tables': []
    }
    
    for table in tables:
        df = table.df
        text = df.to_string().lower()
        
        # Identify table type
        if 'revenue' in text or 'sales' in text:
            if 'operating income' in text or 'net income' in text:
                financial_data['income_statement'] = df
        elif 'asset' in text and 'liabilities' in text:
            financial_data['balance_sheet'] = df
        elif 'cash flow' in text or 'operating activities' in text:
            financial_data['cash_flow'] = df
        else:
            financial_data['other_tables'].append({
                'page': table.page,
                'data': df,
                'accuracy': table.accuracy
            })
    
    return financial_data

financials = extract_financial_tables('annual_report.pdf')
if financials['income_statement'] is not None:
    print("Income Statement found:")
    print(financials['income_statement'])

Example 2: Scientific Data Extraction

import camelot
import pandas as pd

def extract_research_data(pdf_path, pages='all'):
    """Extract data tables from research paper."""
    
    # Try lattice for bordered tables
    tables = camelot.read_pdf(pdf_path, pages=pages, flavor='lattice')
    
    if not tables or all(t.accuracy < 70 for t in tables):
        # Fall back to stream for borderless
        tables = camelot.read_pdf(pdf_path, pages=pages, flavor='stream')
    
    extracted_data = []
    
    for table in tables:
        df = table.df
        
        # Clean up the DataFrame
        # Set first row as header if it looks like one
        if not df.iloc[0].str.contains(r'\d').any():
            df.columns = df.iloc[0]
            df = df[1:]
            df = df.reset_index(drop=True)
        
        extracted_data.append({
            'page': table.page,
            'accuracy': table.accuracy,
            'data': df
        })
    
    return extracted_data

data = extract_research_data('research_paper.pdf')
for i, item in enumerate(data):
    print(f"Table {i+1} (Page {item['page']}, Accuracy: {item['accuracy']}%):")
    print(item['data'].head())

Example 3: Invoice Line Items

Limitations

  • Encrypted PDFs not supported
  • Image-based PDFs need OCR preprocessing
  • Very complex merged cells may need tuning
  • Rotated tables require preprocessing
  • Large PDFs may need page-by-page processing

Installation

pip install camelot-py[cv]

# Additional dependencies
# macOS
brew install ghostscript tcl-tk

# Ubuntu
apt-get install ghostscript python3-tk

$Related Playbooks

Data & Reporting

Scientific Matplotlib

Low-level plotting library for full customization. Use when you need fine-grained control over every plot element, creating novel plot types, or integrating with specific scientific workflows. Export to PNG/PDF/SVG for publication. For quick stati...

5 minutes
Beginner
Data & Reporting

Scientific Networkx

Comprehensive toolkit for creating, analyzing, and visualizing complex networks and graphs in Python. Use when working with network/graph data structures, analyzing relationships between entities, computing graph algorithms (shortest paths, centra...

10 minutes
Intermediate
Data & Reporting

Scientific Plotly

Interactive visualization library. Use when you need hover info, zoom, pan, or web-embeddable charts. Best for dashboards, exploratory analysis, and presentations. For static publication figures use matplotlib or scientific-visualization.

5 minutes
Beginner
Data & Reporting

Scientific Polars

Fast in-memory DataFrame library for datasets that fit in RAM. Use when pandas is too slow but data still fits in memory. Lazy evaluation, parallel execution, Apache Arrow backend. Best for 1-100GB datasets, ETL pipelines, faster pandas replacemen...

10 minutes
Intermediate
Data & Reporting

Scientific Pymc

Bayesian modeling with PyMC. Build hierarchical models, MCMC (NUTS), variational inference, LOO/WAIC comparison, posterior checks, for probabilistic programming and inference.

15 minutes
Advanced
Data & Reporting

Scientific Pymoo

Multi-objective optimization framework. NSGA-II, NSGA-III, MOEA/D, Pareto fronts, constraint handling, benchmarks (ZDT, DTLZ), for engineering design and optimization problems.

10 minutes
Intermediate
Data & Reporting

Scientific Scientific Schematics

Create publication-quality scientific diagrams using Nano Banana 2 AI with smart iterative refinement. Uses Gemini 3.1 Pro Preview for quality review. Only regenerates if quality is below threshold for your document type. Specialized in neural net...

10 minutes
Intermediate
Data & Reporting

Scientific Scientific Visualization

Meta-skill for publication-ready figures. Use when creating journal submission figures requiring multi-panel layouts, significance annotations, error bars, colorblind-safe palettes, and specific journal formatting (Nature, Science, Cell). Orchestr...

10 minutes
Intermediate
Data & Reporting

Scientific Scikit Learn

Machine learning in Python with scikit-learn. Use when working with supervised learning (classification, regression), unsupervised learning (clustering, dimensionality reduction), model evaluation, hyperparameter tuning, preprocessing, or building...

10 minutes
Intermediate
Data & Reporting

Scientific Seaborn

Statistical visualization with pandas integration. Use for quick exploration of distributions, relationships, and categorical comparisons with attractive defaults. Best for box plots, violin plots, pair plots, heatmaps. Built on matplotlib. For in...

5 minutes
Beginner
Data & Reporting

Scientific Shap

Model interpretability and explainability using SHAP (SHapley Additive exPlanations). Use this skill when explaining machine learning model predictions, computing feature importance, generating SHAP plots (waterfall, beeswarm, bar, scatter, force,...

10 minutes
Intermediate
Data & Reporting

Scientific Simpy

Process-based discrete-event simulation framework in Python. Use this skill when building simulations of systems with processes, queues, resources, and time-based events such as manufacturing systems, service operations, network traffic, logistics...

10 minutes
Intermediate

Browse all Data & Reporting playbooks →