Generate a Python script that extracts text from a given PDF and converts it to CSV. A…
- User
Generate a Python script that extracts text from a given PDF and converts it to CSV. A PDF file
Assistant
Problem: Generate a Python script that extracts text from a given PDF and converts it to CSV. A PDF file
Approach: Python
Let me implement this solution.
Here is a complete solution using Python. This solution uses the pdfplumber library, which is highly effective for extracting text and tables from PDFs while preserving the layout structure necessary for CSV conversion.
1. Prerequisites
You will need to install the
pdfplumberlibrary. Open your terminal or command prompt and run:pip install pdfplumber2. The Python Script
Save the following code as a Python file (e.g.,
extract_pdf.py).This script handles two scenarios:
- Table Extraction: Attempts to find structured tables in the PDF.
- Text Fallback: If no tables are found, it extracts raw text line by line.
import pdfplumber import csv import sys import os def pdf_to_csv(pdf_path, csv_path): """ Extracts text/tables from a PDF and saves it to a CSV file. """ # Check if file exists if not os.path.exists(pdf_path): print(f"Error: The file '{pdf_path}' was not found.") return try: # Open the PDF with pdfplumber.open(pdf_path) as pdf: all_rows = [] print(f"Processing {len(pdf.pages)} pages...") for i, page in enumerate(pdf.pages): # Strategy 1: Try to extract structured tables tables = page.extract_tables() if tables: # If tables are found, iterate through them for table in tables: # Clean up data (remove None types, strip whitespace) cleaned_table = [ [' '.join(str(cell).split()) if cell else '' for cell in row] for row in table ] all_rows.extend(cleaned_table) else: # Strategy 2: Fallback to raw text extraction if no tables found print(f"No tables found on page {i+1}, extractin