Parsing Pdfs And Extracting Data With Python
You’re staring at a PDF report from your company’s quarterly earnings. The table you need — sales by region, with twelve rows and four columns — looks perfect on screen. You try to copy it. What you get is a jumbled mess of numbers and text that looks nothing like the original. You try to paste it into Excel, and it all lands in one cell.
Why is this so hard?
If you’ve ever spent an hour manually retyping numbers from a PDF report, you’re not alone. It’s one of the most frustrating tasks in data work. The good news? By the end of this tutorial, you’ll have a reusable Python script that extracts text, tables, and metadata from any PDF. We’ll use three libraries: pypdf for basic text extraction, pdfplumber for tables and layout, and reportlab to generate a practice PDF so we know exactly what we’re working with.
Let’s start by understanding why PDFs are so stubborn.
What’s Actually Inside a PDF? (The 30-Second Version)
Think of a PDF like a painting of a document, not the document itself. When you look at a PDF, you see paragraphs, tables, and headings. But inside the file, there are no paragraphs or tables. There are just characters placed at specific x,y coordinates on each page.
A PDF is a collection of objects — text strings, images, fonts, annotations — each with a position. It’s like a shopping list of visual elements. The PDF knows that the letter ‘N’ is at position (100, 200) and the letter ‘a’ is at (112, 200), but it has no idea that together they form the word “Name” or that “Name: John” is a label-value pair.
This is why extracting text is hard. The PDF doesn’t understand structure. It only understands where to put things on the page. To extract data, we have to read the painting character by character — and figure out the structure ourselves.
Setting Up: Your PDF Toolkit
First, let’s install the libraries we’ll need. Open your terminal and run:
# In your terminal, run:
# pip install pypdf pdfplumber reportlab
Now, let’s create a practice PDF. We’ll use reportlab to generate a simple document with a title, a paragraph, and a table. This gives us a known ground truth — we know exactly what the PDF should contain, so we can check if our extraction works.
# generate_practice_pdf.py
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Paragraph, Table, TableStyle
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib import colors
# Create a PDF with a title, paragraph, and table
doc = SimpleDocTemplate("practice_report.pdf", pagesize=letter)
styles = getSampleStyleSheet()
# Build the content
story = []
# Title
story.append(Paragraph("Quarterly Sales Report", styles['Title']))
# Paragraph
story.append(Paragraph(
"This report shows sales data for Q1 2024 across four regions. "
"All figures are in thousands of dollars.",
styles['Normal']
))
# Table data
header = ['Region', 'Q1 Sales', 'Q2 Sales', 'Q3 Sales']
data = [
['North', '120', '135', '142'],
['South', '98', '104', '111'],
['East', '145', '158', '167'],
['West', '132', '140', '149']
]
table_data = [header] + data
# Create the table
table = Table(table_data)
table.setStyle(TableStyle([
('BACKGROUND', (0, 0), (-1, 0), colors.grey),
('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
('ALIGN', (0, 0), (-1, -1), 'CENTER'),
('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
('BOTTOMPADDING', (0, 0), (-1, 0), 12),
('BACKGROUND', (0, 1), (-1, -1), colors.beige),
('GRID', (0, 0), (-1, -1), 1, colors.black),
]))
story.append(table)
# Build the PDF
doc.build(story)
print("Practice PDF created: practice_report.pdf")
Run this script, and you’ll get a file called practice_report.pdf. Open it — you should see a title, a short paragraph, and a table with four regions and three quarters of sales data. Now we have a test subject we know inside and out.
Extracting Text with pypdf: The First Pass
Let’s start with the simplest approach — using pypdf to extract the raw text. This is the easiest tool to use, but it has limitations.
# extract_text_pypdf.py
from pypdf import PdfReader
# Open the PDF
reader = PdfReader("practice_report.pdf")
print(f"Number of pages: {len(reader.pages)}")
print("\n" + "="*50)
print("Extracted text from page 0:")
print("="*50)
# Extract text from the first page
page = reader.pages[0]
text = page.extract_text()
print(text)
When you run this, you’ll see something like:
Number of pages: 1
==================================================
Extracted text from page 0:
==================================================
Quarterly Sales Report
This report shows sales data for Q1 2024 across four regions. All figures are in thousands of dollars.
Region Q1 Sales Q2 Sales Q3 Sales
North 120 135 142
South 98 104 111
East 145 158 167
West 132 140 149
It works! The text is all there. But look closely — there are no paragraph breaks, no table structure. The title, paragraph, and table are just one continuous string. The table data is there, but it’s just a line of text: “Region Q1 Sales Q2 Sales Q3 Sales North 120 135 142…”
This is the hardest part of PDF extraction to accept: pypdf gives us the raw text, but it’s like dumping a jigsaw puzzle on the table. All the pieces are there, but they’re not assembled. If you need structured data — like a table you can put into pandas — you’ll need more.
Extracting Tables with pdfplumber: Where the Magic Happens
Now here’s the interesting part. pdfplumber understands layout. It looks for visual clues — lines, spacing, alignment — to figure out where the table boundaries are. It’s like giving the computer a pair of eyes.
# extract_tables_pdfplumber.py
import pdfplumber
# Open the PDF with pdfplumber
with pdfplumber.open("practice_report.pdf") as pdf:
# Get the first page
page = pdf.pages[0]
# Extract tables
tables = page.extract_tables()
print(f"Number of tables found: {len(tables)}")
print("\n" + "="*50)
print("First table:")
print("="*50)
# Print the first table
for row in tables[0]:
print(row)
Run this, and you’ll see:
Number of tables found: 1
==================================================
First table:
==================================================
['Region', 'Q1 Sales', 'Q2 Sales', 'Q3 Sales']
['North', '120', '135', '142']
['South', '98', '104', '111']
['East', '145', '158', '167']
['West', '132', '140', '149']
That’s our table! pdfplumber found it and returned it as a list of lists. Each inner list is a row, and each element is a cell. This is exactly what we need to work with in pandas.
Let’s convert it to a DataFrame:
# table_to_dataframe.py
import pdfplumber
import pandas as pd
# Open the PDF and extract the table
with pdfplumber.open("practice_report.pdf") as pdf:
page = pdf.pages[0]
tables = page.extract_tables()
# Get the first table
table_data = tables[0]
# First row is the header
header = table_data[0]
# Remaining rows are data
data_rows = table_data[1:]
# Create DataFrame
df = pd.DataFrame(data_rows, columns=header)
print("Table as pandas DataFrame:")
print(df)
print("\nData types:")
print(df.dtypes)
You’ll see:
Table as pandas DataFrame:
Region Q1 Sales Q2 Sales Q3 Sales
0 North 120 135 142
1 South 98 104 111
2 East 145 158 167
3 West 132 140 149
Data types:
Region object
Q1 Sales object
Q2 Sales object
Q3 Sales object
dtype: object
The table is now in a DataFrame, ready for analysis. Notice the data types are object (strings) — you’d want to convert the sales columns to numbers. But that’s a small step once you have the structure.
Handling Real-World Messy PDFs: What Can Go Wrong
Our practice PDF is clean. Real PDFs are not. Here are the most common problems you’ll face and how to handle them.
Problem 1: No visible table lines. Some PDFs don’t draw borders around tables. pdfplumber may miss the table entirely. In that case, you’ll need to use page.extract_text() and parse it manually with regular expressions.
Problem 2: Multi-line cells. Text can wrap within a cell, causing one row to split into multiple rows in the extraction. You’ll see a row where the first column is empty — that’s the continuation of the previous row.
Let’s write a function that handles multi-line cells:
# merge_multiline_cells.py
def merge_multiline_rows(table_data):
"""
Merge rows where the first column is empty (continuation of previous row).
Args:
table_data: List of lists from pdfplumber.extract_tables()
Returns:
List of lists with merged rows
"""
merged = []
current_row = None
for row in table_data:
# Check if first column is empty (None or empty string)
first_cell = row[0] if row else None
if first_cell is None or first_cell == '':
# This is a continuation of the previous row
if current_row is not None:
# Append this row's content to the last cell of current row
for i in range(1, len(row)):
if row[i] and row[i].strip():
if i < len(current_row):
current_row[i] = current_row[i] + ' ' + row[i].strip()
else:
# New row
if current_row is not None:
merged.append(current_row)
current_row = list(row)
# Don't forget the last row
if current_row is not None:
merged.append(current_row)
return merged
# Test with a simulated multi-line table
simulated_data = [
['Region', 'Q1 Sales', 'Q2 Sales', 'Q3 Sales'],
['North', '120', '135', '142'],
['', 'This is a', 'continuation', 'of North row'],
['South', '98', '104', '111'],
]
print("Before merge:")
for row in simulated_data:
print(row)
merged_data = merge_multiline_rows(simulated_data)
print("\nAfter merge:")
for row in merged_data:
print(row)
This function checks if the first column is empty. If it is, that row is a continuation of the previous row, and we append its content to the last cell of the current row.
Problem 3: Scanned PDFs. If your PDF is a scanned image (a picture of text), none of these tools will work. You’ll need OCR (Optical Character Recognition) using Tesseract and pytesseract — that’s a topic for a future article.
Real PDFs are like real people — messy and unpredictable. The tools we’ve covered work for 80% of cases. For the other 20%, you need detective work.
Putting It All Together: A Reusable PDF Extraction Script
Let’s combine everything into a single function that extracts text and tables from a PDF and saves them to CSV. This function tries pdfplumber first for tables, falls back to pypdf for text, and handles errors gracefully.
# extract_pdf.py
import pdfplumber
from pypdf import PdfReader
import pandas as pd
import os
def extract_pdf(pdf_path, output_dir='.'):
"""
Extract text and tables from a PDF file.
Args:
pdf_path: Path to the PDF file
output_dir: Directory to save CSV files (default: current directory)
Returns:
dict with 'text' (list of page strings) and 'tables' (list of DataFrames)
"""
result = {
'text': [],
'tables': []
}
# Extract text using pypdf
try:
reader = PdfReader(pdf_path)
for page in reader.pages:
result['text'].append(page.extract_text())
except Exception as e:
print(f"Error extracting text with pypdf: {e}")
# Extract tables using pdfplumber
try:
with pdfplumber.open(pdf_path) as pdf:
for page_num, page in enumerate(pdf.pages):
tables = page.extract_tables()
for table_num, table in enumerate(tables):
if len(table) > 0:
# First row is header
header = table[0]
data_rows = table[1:]
# Create DataFrame
df = pd.DataFrame(data_rows, columns=header)
result['tables'].append(df)
# Save to CSV
base_name = os.path.splitext(os.path.basename(pdf_path))[0]
csv_name = f"{base_name}_page{page_num+1}_table{table_num+1}.csv"
csv_path = os.path.join(output_dir, csv_name)
df.to_csv(csv_path, index=False)
print(f"Saved table to {csv_path}")
except Exception as e:
print(f"Error extracting tables with pdfplumber: {e}")
return result
# Run on our practice PDF
result = extract_pdf("practice_report.pdf")
print("\nExtracted text (first page):")
print(result['text'][0][:200] + "...") # First 200 characters
print(f"\nNumber of tables found: {len(result['tables'])}")
if result['tables']:
print("\nFirst table:")
print(result['tables'][0])
When you run this, you’ll see:
Saved table to practice_report_page1_table1.csv
Extracted text (first page):
Quarterly Sales Report
This report shows sales data for Q1 2024 across four regions. All figures are in thousands of dollars.
Region Q1 Sales Q2 Sales Q3 Sales
North 120 135 142
South 98 104 111
East 145 158 167
West 132 140 149...
Number of tables found: 1
First table:
Region Q1 Sales Q2 Sales Q3 Sales
0 North 120 135 142
1 South 98 104 111
2 East 145 158 167
3 West 132 140 149
We now have a CSV file with our table data, ready for analysis in pandas or Excel. The function is reusable — just point it at any PDF, and it will extract what it can.
What We Learned and Where to Go Next
Let’s recap what we covered:
- PDFs store visual positions, not structure. They’re like paintings of documents, not the documents themselves.
pypdfextracts raw text — it works, but you lose all structure like paragraphs and tables.pdfplumberfinds tables by looking at visual layout — lines, spacing, alignment.- Real PDFs need post-processing. Multi-line cells, missing borders, and scanned pages are common problems.
In the next article, we’ll tackle scanned PDFs using OCR with Tesseract and pytesseract. That’s when the real magic happens — turning images of text into actual, extractable data.
For now, try running the extract_pdf function on a PDF from your own work. You might be surprised at how much you can automate.
Check Your Understanding
-
Remember: What does a PDF store instead of paragraphs or tables?
-
Understand: Why does
pypdf’s text extraction often lose paragraph breaks? -
Apply: Given a PDF with a table that has no visible lines, which tool would you use and what additional step might you need?
-
Analyze: Compare the output of
pypdfandpdfplumberon the same PDF. Why might one miss data the other finds? -
Evaluate: When would you choose
pypdfoverpdfplumber, and vice versa?
Apply What You Learned is for Supporter and Insider subscribers.
Subscribe to unlock the exercises on this post.
See plansRelated articles
- Python Engineering Under review
OCR With Tesseract and Python: Turning Images Into Text Data
You're staring at a scanned PDF of a report, a photo of a restaurant receipt, or a screenshot of a table from a website. The information you need — the numbers, the names, the dates — is *right there* in the image.
- Python Engineering Under review
A Data Science Glossary 100 Terms Explained In Pla
Before we talk about models or metrics, we need to agree on what “data” actually looks like in Python. When you load a CSV file, you’re not staring at raw numbers — you’re staring at a carefully labeled structure.
- Python Engineering Under review
Sending Automated Emails And Reports From A Python
You just spent three hours building a beautiful pandas report. You cleaned the data, created a summary table, made a chart, and exported everything to a CSV file.
- Python Engineering Under review
Python Desktop Gui Frameworks Compared Tkinter Vs
Before we write a single line of code, we need a mental model for comparing these tools. Think of it like choosing a vehicle.
Looking for something else?
Search every article by title, summary or topic.