"""Extract sample.pdf's ruled table using Python 3 and pdfplumber. Run: python3 extract.py Requires pdfplumber (validated with 0.11.9). Paths are relative to this script. """ import csv from pathlib import Path import pdfplumber def main(): root = Path(__file__).resolve().parent with pdfplumber.open(root / "sample.pdf") as pdf: tables = [table for page in pdf.pages for table in page.extract_tables()] if len(tables) != 1: raise ValueError(f"Expected one ruled table, found {len(tables)}") rows = tables[0] if not rows or any(len(row) != 4 or any(cell is None for cell in row) for row in rows): raise ValueError("Expected a complete four-column table") # Keep cells as text to retain displayed precision and column order. # csv.writer quotes product names containing commas automatically. with (root / "table.csv").open("w", encoding="utf-8", newline="") as output: csv.writer(output).writerows(rows) if __name__ == "__main__": main()