Below is a Python example that demonstrates how to read a PDF file, extract its text, and store the extracted text in a Pandas DataFrame. This example uses the PyPDF2 library for reading the PDF and extracting text from simple PDFs, pdfplumber for handling more complex PDFs (such as those with tables or layouts that PyPDF2 might struggle with), and pandas for creating and manipulating the DataFrame. For scanned PDFs or images, pdf2image and pytesseract (via OCR) are used to extract text from images.
Before running the code, ensure you have the necessary libraries installed. You can install them using pip if you haven't already:
import PyPDF2
import pdfplumber
from pdf2image import convert_from_path
import pytesseract
from PIL import Image
import pandas as pd
import os
def extract_text_with_pyPDF2(file_path):
"""
Extracts text from a PDF file using PyPDF2.
Parameters:
- file_path (str): The path to the PDF file.
Returns:
- list: A list of strings where each string represents the text extracted from a page.
"""
pdf_file_obj = open(file_path, 'rb')
pdf_reader = PyPDF2.PdfFileReader(pdf_file_obj)
num_pages = pdf_reader.getNumPages() # Use getNumPages() instead of numPages
text = []
for page in range(num_pages):
page_obj = pdf_reader.getPage(page)
text.append(page_obj.extractText())
pdf_file_obj.close()
return text
def extract_text_with_pdfplumber(file_path):
"""
Extracts text from a PDF file using pdfplumber.
Parameters:
- file_path (str): The path to the PDF file.
Returns:
- list: A list of strings where each string represents the text extracted from a page.
"""
text = []
with pdfplumber.open(file_path) as pdf:
for page in pdf.pages:
text.append(page.extract_text())
return text
def extract_text_with_ocr(file_path):
"""
Extracts text from a PDF file using OCR (for scanned or image-based PDFs).
Parameters:
- file_path (str): The path to the PDF file.
Returns:
- list: A list of strings where each string represents the text extracted from a page.
"""
text = []
images = convert_from_path(file_path)
for img in images:
text.append(pytesseract.image_to_string(img))
return text
def text_to_dataframe(text_list, file_name, method='PyPDF2'):
"""
Converts a list of extracted text into a Pandas DataFrame.
Parameters:
- text_list (list): A list of strings where each string is the text from a PDF page.
- file_name (str): The name of the PDF file (for reference in the DataFrame).
- method (str): The method used for extraction (default='PyPDF2').
Returns:
- pd.DataFrame: A DataFrame with the file name, extraction method, and extracted text.
"""
data = {
"File Name": [file_name] * len(text_list),
"Extraction Method": [method] * len(text_list),
"Page Number": list(range(1, len(text_list) + 1)),
"Extracted Text": text_list
}
df = pd.DataFrame(data)
return df
# Example Usage
if __name__ == "__main__":
pdf_file_path = "path/to/your/document.pdf" # Update this to your PDF file path
file_name = pdf_file_path.split("/")[-1] # Extracts the file name from the path
# Try PyPDF2 first
try:
extracted_text = extract_text_with_pyPDF2(pdf_file_path)
df = text_to_dataframe(extracted_text, file_name, method='PyPDF2')
except Exception as e:
print(f"Error with PyPDF2: {e}")
# If PyPDF2 fails, try pdfplumber
try:
extracted_text = extract_text_with_pdfplumber(pdf_file_path)
df = text_to_dataframe(extracted_text, file_name, method='pdfplumber')
except Exception as e:
print(f"Error with pdfplumber: {e}")
# If both fail, use OCR as a fallback for scanned/image-based PDFs
try:
extracted_text = extract_text_with_ocr(file_path=pdf_file_path)
df = text_to_dataframe(extracted_text, file_name, method='OCR')
except Exception as e:
print(f"Error with OCR: {e}. Please ensure Tesseract-OCR is installed and configured correctly.")
df = None # Set df to None if all methods fail
if df is not None:
# Display the DataFrame
print(df)
# Optional: Save the DataFrame to a CSV file
# df.to_csv(f"{file_name}_extracted_text.csv", index=False)
else:
print("All extraction methods failed. Please check your PDF file or environment setup.")
Important Notes:
PDF Complexity: The accuracy of text extraction can vary greatly depending on the PDF's complexity, especially if the PDF contains a lot of images with text, tables, or if the text is not properly encoded. PyPDF2 works best with PDFs that have text properly embedded. For more complex PDFs, pdfplumber might offer better results, especially with layouts and tables. For scanned PDFs or image-based PDFs, OCR is the best approach.
File Path: Replace "path/to/your/document.pdf" with the actual path to your PDF file.
Saving to CSV: The code includes a commented line to save the DataFrame to a CSV file. Uncomment this if you wish to save the extracted text to a CSV file. The file will be named after your PDF file but with "_extracted_text.csv" appended.
Dependencies: Ensure PyPDF2, pdfplumber, pdf2image, pytesseract, and Pillow are installed in your environment. If not, you can install them using pip as shown at the beginning of this response. Additionally, Tesseract-OCR must be installed and configured correctly on your system for OCR functionality to work.
Tesseract-OCR Configuration: After installing Tesseract-OCR, you may need to specify the path to the executable in your code if the system cannot find it automatically. You can do this by adding: