Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract text from a Specific Area in a PDF using Python?

I'm trying to extract Text from a PDF using Python, and I have successfully done so using PyPDF2 like this:

from PyPDF2 import PdfFileReader
reader = PdfFileReader('path.pdf')
page = reader.getPage(0)
page.extractText()

This extracts all the Text from the Page, but I want to extract the text only from a Rectangular region of 3'x4' at the top-left part of the page.

I Basically want to do something like :How-to extract text from a pdf doc within a specific rectangular region? but in Python

Can this be done by PyPDF2 or by any other Python Library?

like image 770
Devdatta Tengshe Avatar asked Aug 21 '17 07:08

Devdatta Tengshe


People also ask

How do I extract specific text from a PDF in Python?

Step 1: Import all libraries. Step 2: Convert PDF file to txt format and read data. Step 3: Use “. findall()” function of regular expressions to extract keywords.

How do I extract data from a PDF in Python?

All we need to do is use PyPDF2 to access the XML document from the object structure of this file. Once we have access to the XML, it is a simple exercise of parsing out the XML document to access values for various form elements, which could then be stored into a Python list, Numpy array, Pandas dataframe etc.


1 Answers

This is a rather complex topic, but it is possible. First you need to get familiar with the pdf format descripton.

Start here for example.

You can identify the location and contents of the text boxes and extract the string data.

This topic holds examples for pyPdf, the previous version of PyPDF2, but syntax is similar. There are examples on how to iterate through the indirect objects.

A good place to start is also the source of the function pageObj.extractText() that you used.

If you are not restricted to Python: How to extract text from a PDF?

You can also use a tool like iText RUPS to inspect the pdf. It shows how the content is rendered and placed on the page:

enter image description here

Afterwards you should be able to identify and address the elements and extract their content.

like image 111
Joe Avatar answered Oct 14 '22 02:10

Joe