DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Python and Open-Source Libraries for Efficient PDF Management
  • Implementing a RAG Model for PDF Content Extraction and Query Answering
  • Python Techniques for Text Extraction From Images
  • Reversing an Array: An Exploration of Array Manipulation

Trending

  • After 9 Years, Microsoft Fulfills This Windows Feature Request
  • Unlocking the Potential of Apache Iceberg: A Comprehensive Analysis
  • Mastering Deployment Strategies: Navigating the Path to Seamless Software Releases
  • How To Build AI-Powered Prompt Templates Using the Salesforce Prompt Builder
  1. DZone
  2. Data Engineering
  3. Data
  4. Extracting PDF Metadata and Text With Python

Extracting PDF Metadata and Text With Python

In this post, we take a look at how to use Python and some cool Python packages to extract a few different types of data from PDFs. Read on to get started!

By 
Mike Driscoll user avatar
Mike Driscoll
·
Updated Sep. 26, 18 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
29.9K Views

Join the DZone community and get the full member experience.

Join For Free

There are lots of PDF-related packages for Python. One of my favorites is PyPDF2. You can use it to extract metadata, rotate pages, split or merge PDFs, and more. It's kind of a Swiss-army knife for existing PDFs. In this article, we will learn how to extract basic information about a PDF using PyPDF2.

Getting Started

PyPDF2 doesn't come as a part of the Python Standard Library, so you will need to install it yourself. The preferred way to do so is to use pip.

pip install pypdf2

Now that we have PyPDF2 installed, let's learn how to get metadata from a PDF!

Extracting Metadata

You can use PyPDF2 to extract a fair amount of useful data from any PDF. For example, you can learn the author of the document, its title and subject, and how many pages there are. Let's find out how by downloading the sample of this book from Leanpub at https://leanpub.com/reportlab. The sample I downloaded was called "reportlab-sample.pdf".

Here's the code:

# get_doc_info.py

from PyPDF2 import PdfFileReader


def get_info(path):
    with open(path, 'rb') as f:
        pdf = PdfFileReader(f)
        info = pdf.getDocumentInfo()
        number_of_pages = pdf.getNumPages()

    print(info)

    author = info.author
    creator = info.creator
    producer = info.producer
    subject = info.subject
    title = info.title

if __name__ == '__main__':
    path = 'reportlab-sample.pdf'
    get_info(path)

Here we import the PdfFileReader class from PyPDF2. This class gives us the ability to read a PDF and extract data from it using various accessor methods. The first thing we do is create our own get_info function that accepts a PDF file path as its only argument. Then we open the file in read-only binary mode. Next, we pass that file handler into PdfFileReader and create an instance of it.

Now we can extract some information from the PDF by using the getDocumentInfo method. This will return an instance of PyPDF2.pdf.DocumentInformation, which has the following useful attributes, among others:

  • author
  • creator
  • producer
  • subject
  • title

If you print out the DocumentInformation object, this is what you will see:

{ '/Author': 'Michael Driscoll',
 '/CreationDate': "D:20180331023901-00'00'",
 '/Creator': 'LaTeX with hyperref package',
 '/Producer': 'XeTeX 0.99998',
 '/Title': 'ReportLab - PDF Processing with Python' }

We can also get the number of pages in the PDF by calling the getNumPages method.

Extracting Text From PDFs

PyPDF2 has limited support for extracting text from PDFs. It doesn't have built-in support for extracting images, unfortunately. I have seen some recipes on Stack Overflow that use PyPDF2 to extract images, but the code examples seem to be pretty hit or miss.

Let's try to extract the text from the first page of the PDF that we downloaded in the previous section:

# extracting_text.py

from PyPDF2 import PdfFileReader


def text_extractor(path):
    with open(path, 'rb') as f:
        pdf = PdfFileReader(f)

        # get the first page
        page = pdf.getPage(1)
        print(page)
        print('Page type: {}'.format(str(type(page))))

        text = page.extractText()
        print(text)


if __name__ == '__main__':
    path = 'reportlab-sample.pdf'
    text_extractor(path)

You will note that this code starts out in much the same way as our previous example. We still need to create an instance of PdfFileReader. But, this time, we grab a page using the getPage method. PyPDF2 is zero-based, much like most things in Python, so when you pass it a one, it actually grabs the second page. The first page, in this case, is just an image, so it wouldn't have any text.

Interestingly, if you run this example you will find that it doesn't return any text. Instead, all I got was a series of line break characters. Unfortunately, PyPDF2 has pretty limited support for extracting text. Even if it is able to extract text, it may not be in the order you expect and the spacing may be different as well.

To get this example code to work, you will need to try running it against a different PDF. I found one on the United States Internal Revenue Service website here: https://www.irs.gov/pub/irs-pdf/fw9.pdf

This is a W9 form for people who are self-employed or contract employees. It can be used in other situations too. Anyway, I downloaded it as w9.pdf and added it to the GitHub repository as well. If you use that PDF instead of the sample one, it will happily extract some of the text from page 2. I won't reproduce the output here as it is kind of lengthy though.

You may find that the pdfminer package works better for extracting text than PyPDF2 though.

Wrapping Up

The PyPDF2 package is quite useful. We were able to get some helpful information from PDFs using it. I could see using PyPDF on a folder of PDFs and using the metadata extraction technique to sort out the PDFs by creator name, subject, etc. Give it a try and see what you think!

PDF Metadata Python (language) Extract

Published at DZone with permission of Mike Driscoll, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Python and Open-Source Libraries for Efficient PDF Management
  • Implementing a RAG Model for PDF Content Extraction and Query Answering
  • Python Techniques for Text Extraction From Images
  • Reversing an Array: An Exploration of Array Manipulation

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!