# Extract tables from a PDF in Python: scripts and outputs
Checked 2026-11-07. Every script ran as shown; the lines under # $ are what it printed, cut only where you see ....
Contents
- table-larkspur.pdf is parserkit’s public sample at https://parserkit.com/samples/table-larkspur.pdf (2 pages, 52 rows, no ruling lines).
- larkspur-trade.pdf is a ruled table with merged cells, made with reportlab 5.1.0 by make_merged.py below.
- larkspur-scan.pdf is page 1 of table-larkspur.pdf rendered at 150 dpi, turned 1.6 degrees, with speckle noise, saved as an image-only PDF.
# PDFPLUMBER_PY
import pdfplumber
TEXT = {"vertical_strategy": "text", "horizontal_strategy": "text"}
with pdfplumber.open("table-larkspur.pdf") as pdf:
for page in pdf.pages:
ruled = page.extract_tables()
rows = page.extract_tables(TEXT)[0]
print(f"page {page.page_number}: {len(ruled)} tables from lines, text strategy {len(rows)} rows x {len(rows[0])} columns")
if page.page_number == 1:
first_rows = rows[:5]
for row in first_rows:
print(row)
# $ python tables_pdfplumber.py
# page 1: 0 tables from lines, text strategy 61 rows x 8 columns
# page 2: 0 tables from lines, text strategy 51 rows x 7 columns
# ['Whole', 'sale price', 'list, spring 2', '027', '', '', '', '']
# ['', '', '', '', '', '', '', '']
# ['rices in EUR', 'per plant, excluding V', 'AT. Minimum order per line i', 'n plant', 's.', '', '', '']
# ['', '', '', '', '', '', '', '']
# ['CODE', 'PLANT', '', 'POT', 'HEIGHT', 'PRICE', '(EUR) MIN.', 'ORDER']
# CAMELOT_PY
import camelot
for flavor in ["lattice", "stream", "network", "hybrid"]:
tables = camelot.read_pdf("table-larkspur.pdf", pages="1-2", flavor=flavor)
print(flavor, [(t.page, t.shape, round(t.parsing_report["accuracy"], 2)) for t in tables])
page_two = camelot.read_pdf("table-larkspur.pdf", pages="2", flavor="network")[0].df
print(page_two.iloc[0].tolist())
# $ python tables_camelot.py
# lattice []
# stream [(1, (31, 5), 98.85), (1, (31, 5), 99.77), (2, (26, 6), 99.34)]
# network [(1, (29, 6), 100.0), (2, (26, 6), 99.29)]
# hybrid [(1, (29, 6), 100.0), (2, (26, 6), 99.29)]
# ['Wholesale price list, spring 2027', '', '', '', '', 'Larkspur Hollow Nursery']
# MERGED_PY
import camelot
import pdfplumber
with pdfplumber.open("larkspur-trade.pdf") as pdf:
rows = pdf.pages[0].extract_tables()[0]
print("pdfplumber", rows[1:4])
plain = camelot.read_pdf("larkspur-trade.pdf", flavor="lattice")[0].df
filled = camelot.read_pdf("larkspur-trade.pdf", flavor="lattice", copy_text=["v", "h"])[0].df
print("lattice", plain.iloc[1:4, :3].values.tolist())
print("copy_text", filled.iloc[1:4, :3].values.tolist())
# $ python tables_merged.py
# pdfplumber [[None, None, '1-9', '10-49', '50+'], ['Trees', "Acer palmatum 'Bloodgood'", '24.50', '22.80', '21.10'], [None, "Betula utilis 'Doorenbos'", '58.00', '54.00', '50.50']]
# lattice [['', '', '1-9'], ['Trees', "Acer palmatum 'Bloodgood'", '24.50'], ['', "Betula utilis 'Doorenbos'", '58.00']]
# copy_text [['GROUP', 'PLANT', '1-9'], ['Trees', "Acer palmatum 'Bloodgood'", '24.50'], ['Trees', "Betula utilis 'Doorenbos'", '58.00']]
# SCAN_PY
import camelot
import pdfplumber
import pytesseract
print(camelot.read_pdf("larkspur-scan.pdf", flavor="stream").n, "tables from camelot")
with pdfplumber.open("larkspur-scan.pdf") as pdf:
page = pdf.pages[0]
print(len(page.chars), "characters in the text layer")
image = page.to_image(resolution=300).original
lines = [line for line in pytesseract.image_to_string(image).splitlines() if "LH" in line]
for line in lines[:8]:
print(ascii(line))
# $ python tables_scan.py
# .../camelot/parsers/base.py:132: UserWarning: page-1 is image-based, camelot only works on text-based pages.
# warnings.warn(
# 0 tables from camelot
# 0 characters in the text layer
# 'LH-1001 Acer palmatum \u2018Bloodgood c10. 80-100 cm 24.50 | 5'
# "LH-1002 Acer palmatum 'Sango-kaku' - C10 80-100 cm \u2014 26.80 sy"
# '. LH-1003 i Amelanchier jamarcelle | 15 125-150 cm. 31.20, 3'
# "\u2018LH-1004 Betula utilis \u2018Doorenbos' ~ \u20ac25 200-250 cm : 58.00 2"
# '. LH-1005 Buxus sempervirens: C2 20-25 cm 3,15" 25'
# 'LH-1006 Carpinus betulus | \xa23 60-80 cm 4.90. 25'
# 'LH-1007 Cornus alba \u2018Sibirica\u2019 C3. 40-60 cm 4.40 10\xb0'
# '. LH-1009 Euonymus alatus \u2018Compactus\u2019 . C5: 40-50 cm 9.80 10'
# SCAN_OCR_PY
import re
import subprocess
import camelot
subprocess.run(["ocrmypdf", "--deskew", "--quiet", "larkspur-scan.pdf", "larkspur-scan-ocr.pdf"], check=True)
def rows_by_code(table):
rows = {}
for row in table.df.values.tolist():
text = re.sub(r"[^\w.-]", "", "".join(row))
if text.startswith("LH-"):
rows[text[:7]] = (text, [" ".join(cell.split()) for cell in row])
return rows
digital = {code: text for code, (text, _) in rows_by_code(camelot.read_pdf("table-larkspur.pdf", flavor="network")[0]).items()}
for flavor in ["stream", "network", "hybrid"]:
tables = camelot.read_pdf("larkspur-scan-ocr.pdf", flavor=flavor)
found = {}
for table in tables:
for code, row in rows_by_code(table).items():
if code not in found or row[0] == digital.get(code):
found[code] = row
right = [code for code, (text, _) in found.items() if text == digital.get(code)]
print(f"{flavor}: {tables.n} tables, {len(found)} of 28 rows found, {len(right)} read right")
wrong = [cells for code, (text, cells) in sorted(found.items()) if text != digital.get(code)]
for cells in wrong[:3]:
print(ascii(cells))
# $ python tables_scan_ocr.py
# stream: 1 tables, 28 of 28 rows found, 10 read right
# network: 1 tables, 25 of 28 rows found, 9 read right
# hybrid: 6 tables, 28 of 28 rows found, 10 read right
# ['LH-1001', 'Acer palmatum \u2018Bloodgood\u2019', 'C10.', '80-100 cm', '24.50', '5']
# ['LH-1005', 'Buxus sempervirens', 'c2', '20-25 cm', 'S15:', '25']
# ['LH-1006 = Carpinus betulus', '', 'cS)', '60-80 cm', '4.90', '25']
# VERSIONS_PY
import platform
import subprocess
import sys
from importlib.metadata import version
TOOLS = {
"tesseract": lambda: subprocess.run(["tesseract", "--version"], capture_output=True, text=True).stdout.split()[1],
"ollama": lambda: subprocess.run(["ollama", "--version"], capture_output=True, text=True).stdout.split()[-1],
"libreoffice": lambda: subprocess.run(["soffice", "--version"], capture_output=True, text=True).stdout.split()[1],
}
print("Python", platform.python_version())
for name in sys.argv[1:]:
print(name, TOOLS[name]() if name in TOOLS else version(name))
# $ python versions.py pdfplumber camelot-py pytesseract ocrmypdf tesseract
# Python 3.12.14
# pdfplumber 0.11.10
# camelot-py 2.0.0
# pytesseract 0.3.13
# ocrmypdf 17.13.0
# tesseract 5.5.0
# make_merged.py
from reportlab.lib import colors
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.units import mm
from reportlab.platypus import Paragraph, SimpleDocTemplate, Spacer, Table, TableStyle
styles = getSampleStyleSheet()
rows = [
["GROUP", "PLANT", "PRICE PER PLANT (EUR)", "", ""],
["", "", "1-9", "10-49", "50+"],
["Trees", "Acer palmatum 'Bloodgood'", "24.50", "22.80", "21.10"],
["", "Betula utilis 'Doorenbos'", "58.00", "54.00", "50.50"],
["", "Malus 'Evereste'", "64.00", "59.50", "55.70"],
["Shrubs", "Cornus kousa 'China Girl'", "42.60", "39.60", "37.00"],
["", "Hydrangea paniculata 'Limelight'", "11.90", "11.10", "10.40"],
["", "Pieris japonica 'Mountain Fire'", "13.90", "12.90", "12.10"],
["Perennials", "Salvia nemorosa 'Caradonna'", "2.25", "2.10", "1.95"],
["", "Geranium 'Rozanne'", "2.90", "2.70", "2.50"],
]
table = Table(rows, colWidths=[30 * mm, 70 * mm, 24 * mm, 24 * mm, 24 * mm], rowHeights=8 * mm)
table.setStyle(
TableStyle(
[
("GRID", (0, 0), (-1, -1), 0.6, colors.HexColor("#3c6e3a")),
("SPAN", (0, 0), (0, 1)),
("SPAN", (1, 0), (1, 1)),
("SPAN", (2, 0), (4, 0)),
("SPAN", (0, 2), (0, 4)),
("SPAN", (0, 5), (0, 7)),
("SPAN", (0, 8), (0, 9)),
("FONTNAME", (0, 0), (-1, 1), "Helvetica-Bold"),
("FONTSIZE", (0, 0), (-1, -1), 9),
("BACKGROUND", (0, 0), (-1, 1), colors.HexColor("#e3e8e2")),
("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
("ALIGN", (2, 0), (-1, -1), "RIGHT"),
("ALIGN", (2, 0), (4, 1), "CENTER"),
]
)
)
doc = SimpleDocTemplate("larkspur-trade.pdf", pagesize=A4, title="Larkspur Hollow Nursery trade prices", leftMargin=18 * mm, rightMargin=18 * mm)
doc.build(
[
Paragraph("Larkspur Hollow Nursery", styles["Heading3"]),
Paragraph("Trade prices by quantity, spring 2027", styles["Title"]),
Paragraph("Prices in EUR per plant, excluding VAT.", styles["Normal"]),
Spacer(1, 6 * mm),
table,
]
)
End