Extract specific text from pdf using python

2.1k views Asked by At

How to extract specific text from a pdf using python?

ex: Pdf contain ( Name: Python , Color: Blue ). In that case I want to extract whatever text that comes after "Name:" and not to extract any text after the "," between "Python" and "Color".

Any help is appreciated.

import PyPDF2 

pdf = open("C:\\Users\\ME\\Desktop\\test.pdf)

reader = PyPDF2.PdfReader(pdf)

page = reader.pages[0]

print(page.extract_text())

This extracts the whole pdf.

2

There are 2 answers

1
OM222O On

If your library returns a string, you can use regex to find your desired output:

import re

text = "Name: Python , Color: Blue"
span = re.match("Name:.*,", text).span()
# Add 5 to starting position to remove "Name:"
print(text[span[0]+5:span[1]])
0
Jorj McKie On

Try this using the PyMuPDF package.

import fitz  # PyMuPDF
doc=fitz.open("test.pdf")
page = doc[0]

blocks = page.get_text("blocks")  # extract text separated by paragraphs

# a block is a tuple starting with 4 floats followed by lines in paragraph
for b in blocks:
    lines = b[4].splitlines()  # lines in the paragraph
    for line in lines:  # look for lines having 'Name:' and 'Color:'
        p1 = line.find("Name:")
        if p1 < 0:
            continue
        p2 = line.fine("Color:", p1)
        if p2 < 0:
            continue
        text = line[p1+5:p2]  # all text in between
        p3 = text.find(",")  # find any comma
        if p3 >= 0:  # there, shorten text accordingly
            text = text[:p3]
        # finished