PDF files are widely used for reports, invoices, e-books, forms, and business documents. Sometimes, you need to extract their text for analysis or further processing.
Python makes this task easy with the pypdf library. You can use it to read PDF files, access document metadata, count pages, and extract text from individual pages.
In this tutorial, you will learn how to extract text from a PDF using Python. You will also learn how to read PDF metadata and process multiple pages.
What Is PDF Text Extraction in Python?
PDF text extraction is the process of reading text stored inside a PDF document using a program.
For example, you might want to extract invoice details, read a report, or collect text from multiple PDF files.
Python provides several libraries for PDF processing. In this tutorial, we will use pypdf, a library for reading and manipulating PDF documents.
Note: Text extraction works best with PDFs containing selectable text. Scanned PDFs usually require OCR (Optical Character Recognition).
1. Install the Required Python Library
First, install the pypdf library using pip.
Open your terminal or command prompt and run:
pip install pypdfIf your system uses Python 3 and the command above does not work, try:
python -m pip install pypdfAfter installation, you can import the library into your Python program.
2. Download a Sample PDF File
For testing, you can use your own PDF document or download a sample PDF.
Save the file in the same directory as your Python script. Name it sample.pdf.
You can also use this sample PDF link:
Before running the program, confirm that the file exists in the expected directory.
3. Python Program to Extract Text from a PDF
Create a Python file named pdf_extractor.py.
Add the following code:
from pypdf import PdfReader pdf_path = "sample.pdf" with open(pdf_path, "rb") as file: reader = PdfReader(file) print("Number of pages:", len(reader.pages)) for page_number, page in enumerate(reader.pages, start=1): print(f"\nPage Number: {page_number}") print("-" * 40) text = page.extract_text() if text: print(text) else: print("No extractable text found on this page.") print("-" * 40)
Output
The exact output depends on the PDF file. You will see a result similar to this:
Number of pages: 2
Page Number: 1
----------------------------------------
Text extracted from the first PDF page...
----------------------------------------
Page Number: 2
----------------------------------------
Text extracted from the second PDF page...
----------------------------------------The example output above is illustrative. Your actual output will contain the text extracted from your document.
4. How Does the Code Work?
Let’s understand the important parts of the program.
Import the PdfReader Class
from pypdf import PdfReaderThis statement imports PdfReader from the pypdf library. We use it to open and read PDF documents.
Open the PDF File
with open("sample.pdf", "rb") as file:
reader = PdfReader(file)The open() function opens the PDF in binary read mode. The "rb" mode is suitable for reading binary files such as PDFs.
The with statement automatically closes the file when the block finishes.
Count the PDF Pages
print("Number of pages:", len(reader.pages))The reader.pages collection provides access to the PDF’s pages. Using len() returns the total page count.
Extract Text from Each Page
for page_number, page in enumerate(reader.pages, start=1):
text = page.extract_text()
print(text)The loop processes each page individually. The extract_text() method returns the text that the library can extract from that page.
The enumerate() function also provides the page number, starting at 1.
5. Extract Text from a Specific PDF Page
You do not always need the entire document. You can extract text from a particular page instead.
For example, the following code extracts text from the first page:
from pypdf import PdfReader
reader = PdfReader("sample.pdf")
if len(reader.pages) > 0:
page = reader.pages[0]
text = page.extract_text()
print(text if text else "No extractable text found.")
else:
print("The PDF contains no pages.")Python uses zero-based indexing for the page collection. Therefore, reader.pages[0] refers to the first page, while reader.pages[1] refers to the second.
6. Extract PDF Document Metadata
PDF files can contain metadata such as the title, author, creator, and producer.
You can read available metadata using the following program:
from pypdf import PdfReader reader = PdfReader("sample.pdf") metadata = reader.metadata if metadata: print("Title:", metadata.title) print("Author:", metadata.author) print("Creator:", metadata.creator) print("Producer:", metadata.producer) print("Subject:", metadata.subject) else: print("No PDF metadata found.")
Example Output
Title: Sample Document
Author: Document Author
Creator: PDF Generator
Producer: PDF Library
Subject: Sample PDFThese values are examples only. The actual metadata depends on the PDF file.
Some PDFs do not contain all these fields. In that case, the corresponding values may be None.
7. Extract Text and Save It to a Text File
You can also save the extracted PDF text to a .txt file. This makes it easier to search, analyze, or process the content later.
from pypdf import PdfReader
reader = PdfReader("sample.pdf")
with open("extracted_text.txt", "w", encoding="utf-8") as output_file:
for page_number, page in enumerate(reader.pages, start=1):
text = page.extract_text() or ""
output_file.write(f"\n--- Page {page_number} ---\n")
output_file.write(text)
output_file.write("\n")
print("Text extraction completed.")After running the program, Python creates extracted_text.txt in the current working directory.
The file contains the extracted text, separated by page numbers. If a page has no extractable text, its section may remain empty.
8. Common Problems When Extracting PDF Text
PDF text extraction may not always produce perfect results. Here are some common issues and their solutions.
Problem 1: No Text Is Extracted
Some PDF files contain scanned images rather than selectable text.
Solution: Use an OCR library or tool, such as Tesseract OCR, to recognize text from page images. The pypdf library does not perform OCR itself.
Problem 2: The PDF File Is Not Found
Python may raise a FileNotFoundError when it cannot find the specified file.
Solution: Check the file name and path. You can also provide the complete file path instead of using sample.pdf.
Problem 3: Extracted Text Has Incorrect Spacing
PDFs can store text in complex layouts. Columns, tables, unusual fonts, and positioning may affect the extracted text order.
Solution: Inspect the output and consider layout-aware extraction tools when preserving document structure is important.
Problem 4: The PDF Is Password-Protected
An encrypted PDF may require a password before you can read its pages.
Solution: If you have permission to access the document, use the library’s decryption functionality with the correct password.
9. Other Applications of the pypdf Library
Besides extracting text, pypdf supports several PDF operations.
Merge PDFs: Combine multiple PDF files into one document.
Split PDFs: Create separate documents from selected pages.
Rotate pages: Change the rotation of PDF pages.
Read metadata: Access available document information.
Encrypt PDFs: Apply password-based encryption.
Decrypt PDFs: Access encrypted documents when you have the required password.
Add pages: Assemble new PDF documents from existing pages.
These features make pypdf useful for automating common PDF-processing tasks.
FAQs
How can I extract text from a PDF using Python?
Install the pypdf library and use PdfReader to open the document. Then call extract_text() on each page.
Which Python library is best for PDF text extraction?
pypdf is a useful choice for straightforward PDF reading and text extraction. For scanned documents, you will need OCR. For complex layouts, another specialized extraction tool may work better.
Can Python extract text from scanned PDF files?
Not directly with pypdf alone. Scanned PDFs usually store pages as images, so you need OCR software to recognize the text.
How do I extract text from all pages of a PDF?
Iterate through reader.pages and call extract_text() for each page.
Can I extract PDF metadata using Python?
Yes. The reader.metadata property provides available metadata, such as the title, author, creator, and producer.
