Extract text, tables, and data from PDF documents
This skill provides capabilities for extracting text, tables, and structured data from PDF documents, particularly useful for construction documents, specifications, and reports.
Python 3.7+ with:
pypdf or PyPDF2 - Basic PDF text extractionpdfplumber - Table extraction (recommended)tabula-py - Advanced table extraction (requires Java)pytesseract - OCR for scanned PDFs (optional)When a user needs to extract data from PDFs:
# Extract text from PDF
python scripts/extract_text.py --file "spec.pdf" --pages "1-10"
# Extract tables
python scripts/extract_tables.py --file "bid_tab.pdf" --output "tables.xlsx"
# Search PDF content
python scripts/search_pdf.py --file "spec.pdf" --query "prevailing wage"
# Extract CALTRANS specifications
python scripts/extract_spec.py --file "specs.pdf" --format "caltrans"
import pdfplumber
with pdfplumber.open('document.pdf') as pdf:
full_text = ''
for page in pdf.pages:
full_text += page.extract_text() + '\n'
print(full_text)
import pdfplumber
with pdfplumber.open('bid_tab.pdf') as pdf:
for page_num, page in enumerate(pdf.pages, 1):
tables = page.extract_tables()
for i, table in enumerate(tables):
print(f"Page {page_num}, Table {i+1}")
for row in table:
print(row)
import pdfplumber
import re
with pdfplumber.open('specs.pdf') as pdf:
for page in pdf.pages:
text = page.extract_text()
# Find specific sections
if 'SECTION 200' in text:
# Extract this section
section_text = text
print(section_text)
import pdfplumber
import pandas as pd
tables_data = []
with pdfplumber.open('report.pdf') as pdf:
for page in pdf.pages:
tables = page.extract_tables()
for table in tables:
if table and len(table) > 1:
# Convert to DataFrame
df = pd.DataFrame(table[1:], columns=table[0])
tables_data.append(df)
# Save all tables to Excel
with pd.ExcelWriter('extracted_tables.xlsx') as writer:
for i, df in enumerate(tables_data):
df.to_excel(writer, sheet_name=f'Table_{i+1}', index=False)
For bid tabulation sheets:
For specification documents:
For plan sheets with quantities:
Common issues and solutions:
Empty or garbled text:
Missing tables:
Performance issues:
User Request: "Extract the bid item list from the bid tabulation PDF and convert to Excel"
Your Process:
extract_tables.py to extract all tablesimport pytesseract
from pdf2image import convert_from_path
# Convert PDF to images
images = convert_from_path('scanned.pdf')
# OCR each page
text = ''
for i, image in enumerate(images):
text += pytesseract.image_to_string(image)
text += f'\n--- Page {i+1} ---\n'
print(text)
import pdfplumber
with pdfplumber.open('drawing.pdf') as pdf:
page = pdf.pages[0]
# Extract text with positions
words = page.extract_words()
for word in words:
print(f"{word['text']} at ({word['x0']}, {word['top']})")