HappiomHappiom
  • Self-Improvement
  • Relationship
  • AI for Life
  • Apps
  • Tech
  • More
    • Online Diary
    • Glossary
  • Learn
    • Book
    • >> Soft Skills
    • Time Management
    • >> Tech Skills
    • R
    • Linux
    • Python
  • Our Apps
    • Download Diary App
    • Write Your First Diary
    • Login to Online Diary App
    • 100K+ Famous Quotes Site
  • Resources
    • Self-Improvement Guide
      • 21-Days to Self-Improvement
      • Creating a Habit
      • Learn Life Experiences
      • Easily Prioritizing Tasks
      • Learning from Mistakes
      • Doing Regular Exercises
      • Setting Priority for Success
      • Avoiding Common Mistakes
      • Eating Healthy Food Regularly
    • Journaling Guide
      • Online Diary
      • Best Diary Apps
      • Diary Writing Ideas
      • Diary Writing Topics
      • Avoid Writing in Diary
      • Diary Writing as Hobby
      • Reasons to Write a Diary
      • Types of Feelings In Diary
      • Improve Diary Writing Skills
  • Self-Improvement
  • Relationship
  • AI for Life
  • Apps
  • Tech
  • More
    • Online Diary
    • Glossary
  • Learn
    • Book
    • >> Soft Skills
    • Time Management
    • >> Tech Skills
    • R
    • Linux
    • Python
  • Our Apps
    • Download Diary App
    • Write Your First Diary
    • Login to Online Diary App
    • 100K+ Famous Quotes Site
  • Resources
    • Self-Improvement Guide
      • 21-Days to Self-Improvement
      • Creating a Habit
      • Learn Life Experiences
      • Easily Prioritizing Tasks
      • Learning from Mistakes
      • Doing Regular Exercises
      • Setting Priority for Success
      • Avoiding Common Mistakes
      • Eating Healthy Food Regularly
    • Journaling Guide
      • Online Diary
      • Best Diary Apps
      • Diary Writing Ideas
      • Diary Writing Topics
      • Avoid Writing in Diary
      • Diary Writing as Hobby
      • Reasons to Write a Diary
      • Types of Feelings In Diary
      • Improve Diary Writing Skills
Expand All Collapse All
  • Python Examples
    • Basic Syntax
      • Python Example Code to Concat 2 Numbers
      • Python Example Code to Concat N Strings
      • Python Code to Find Perimeter of a Circle
      • Python Code to Convert CSV file to Parquet format
      • Python Code to Get Current Day of Week
      • Python Code to Convert Binary String to Decimal Number Vice versa
      • Python Code to Find Difference Between 2 Strings
      • Python Example Code to Remove Duplicates from a List
      • Python Example Code to Calculate Height of Triangle
      • Python Code to Generate Complex Random Password
    • File Handling
      • Python Code to Write & Read Key Value Pair in File
      • In Python File is Not Opening (How to Fix)
      • Python Code to Read Specific Line from a File
      • Python Code to Clear Contents of a File
      • Python Code to Count and List Files in a Directory
    • Modules and Libraries
      • Python Code for Automation using BDD
      • Python Code to Load .SO File (and Invoke a Function)
    • Object-Oriented Programming
      • Python Code to Create a Class with Attributes
      • Python Code to Define Methods in a Class
    • Python Example Code to Check Internet Connection
    • Example Python Code to Send an Email
    • Python Code to Fetch Data from an API (e.g., OpenWeatherMap)
    • Example Python Code to Extract Text from PDF
    • Python Code to Perform Web Scraping (e.g., Scraping Wikipedia)
    • Example Python Code to Plot Data Using Matplotlib
    • Python Code to Perform Data Analysis with Pandas
    • Example Python Code to Train a Simple Machine Learning Model (e.g., Linear Regression)
    • Python Code to Handle User Authentication in Flask
    • Example Python Code to interact with databases using libraries like SQLAlchemy

Example Python Code to Extract Text from PDF

Extracting text from a PDF in Python can be efficiently accomplished using libraries designed for PDF manipulation. The `PyMuPDF` and `PyPDF2` libraries are commonly used for this purpose. They provide straightforward methods to read and extract text from PDF documents, making it easier to handle and analyze the content programmatically.

Method 1: Using PyMuPDF

In this example, I’ll demonstrate how to use `PyMuPDF` to extract text from a PDF file. You’ll need to install the library and specify the path to your PDF document. The code reads the PDF, extracts the text, and prints it out.

This approach is useful for automating text extraction tasks and integrating PDF content into your applications.

Certainly! Below is a working example of how to extract text from a PDF using the `PyMuPDF` library in Python.

Prerequisites

1. Install the `PyMuPDF` library if you haven’t already. You can install it using pip:

pip install pymupdf

2. Prepare a PDF file to test the code. Ensure you have the path to this file ready.

Example Code

Let’s write a Python script that uses `PyMuPDF` to extract and print text from each page of a PDF document:

import fitz # PyMuPDF

def extract_text_from_pdf(pdf_path):
# Open the PDF file
document = fitz.open(pdf_path)

# Iterate through each page
for page_num in range(len(document)):
# Get a page
page = document.load_page(page_num)

# Extract text from the page
text = page.get_text()

# Print the extracted text
print(f"Page {page_num + 1}:\n{text}\n{'-'*40}")

# Close the document
document.close()

# Specify the path to your PDF file
pdf_path = 'path_to_your_pdf_file.pdf'

# Extract and print text from the PDF
extract_text_from_pdf(pdf_path)

Explanation

1. Import `fitz`: This is the module provided by `PyMuPDF` for PDF handling.
2. Open the PDF: `fitz.open(pdf_path)` opens the PDF file specified by the path.
3. Iterate Through Pages: The script loops through each page of the PDF using `range(len(document))`.
4. Extract Text: `page.get_text()` extracts text from the current page.
5. Print Text: The text is printed along with the page number, and a separator is added for clarity.
6. Close the Document: Always close the document after processing to free resources.

Notes

  • Error Handling: For robustness, consider adding error handling to manage cases where the file path is incorrect or the PDF is corrupted.
  • Text Quality: The quality of text extraction may vary depending on the PDF’s format and content (e.g., scanned images versus text-based PDFs).

Replace `’path_to_your_pdf_file.pdf’` with the actual path to your PDF file to test the code.

Method 2: Using PyPDF2

Another popular method for extracting text from a PDF in Python is by using the `PyPDF2` library.

Let’s see how you can do it with `PyPDF2`.

Prerequisites

1. Install the `PyPDF2` library if you haven’t already. You can install it using pip:

pip install PyPDF2

2. Prepare a PDF file to test the code. Ensure you have the path to this file ready.

Example Code

Let’s write a Python script that uses `PyPDF2` to extract and print text from each page of a PDF document.

import PyPDF2

def extract_text_from_pdf(pdf_path):
# Open the PDF file in read-binary mode
with open(pdf_path, 'rb') as file:
# Create a PDF reader object
reader = PyPDF2.PdfFileReader(file)

# Iterate through each page
for page_num in range(reader.numPages):
# Get a page
page = reader.getPage(page_num)

# Extract text from the page
text = page.extract_text()

# Print the extracted text
print(f"Page {page_num + 1}:\n{text}\n{'-'*40}")

# Specify the path to your PDF file
pdf_path = 'path_to_your_pdf_file.pdf'

# Extract and print text from the PDF
extract_text_from_pdf(pdf_path)

Explanation

1. Import `PyPDF2`: This library is used for reading and manipulating PDF files.
2. Open the PDF: The PDF file is opened in binary read mode (`’rb’`).
3. Create a PDF Reader: `PyPDF2.PdfFileReader(file)` creates a reader object for the PDF file.
4. Iterate Through Pages: The script loops through each page of the PDF using `range(reader.numPages)`.
5. Extract Text: `page.extract_text()` extracts text from the current page.
6. Print Text: The text is printed along with the page number, and a separator is added for clarity.

Notes

  • Text Extraction Quality: `PyPDF2` is suitable for text-based PDFs. For scanned images or complex PDFs, text extraction might not be as accurate.
  • Error Handling: For more robust error handling, you can add checks to handle cases where the file might be missing or corrupted.

Replace `’path_to_your_pdf_file.pdf’` with the actual path to your PDF file to test the code. This method provides a good alternative to `PyMuPDF` for extracting text from PDFs.

Related Articles
  • Python Example Code to Calculate Height of Triangle
  • Python Example Code to Remove Duplicates from a List
  • Example Python Code to interact with databases using libraries like SQLAlchemy
  • Python Code to Handle User Authentication in Flask
  • Example Python Code to Train a Simple Machine Learning Model (e.g., Linear Regression)
  • Python Code to Perform Data Analysis with Pandas

No luck finding what you need? Contact Us

Previously
Python Code to Fetch Data from an API (e.g., OpenWeatherMap)
Up Next
Python Code to Perform Web Scraping (e.g., Scraping Wikipedia)
  • About Us
  • Contact Us
  • Archive
  • Hindi
  • Tamil
  • Telugu
  • Marathi
  • Gujarati
  • Malayalam
  • Kannada
  • Privacy Policy
  • Copyright 2026 Happiom. All Rights Reserved.