Python3 - Determing if a PDF is scanned or "searchable" I am in a situation where I need to determine if a PDF file is either:


Scanned
Searchable (contain text)


To do this, I am simply running the command pdffonts on the PDF file:

# Check if the resource definition indicates this is a scanned PDF
cmd = ['pdffonts', pdf_file]
proc = subprocess.Popen(
    cmd, stdout=subprocess.PIPE, bufsize=0, text=True, shell=False)
out, err = proc.communicate()

scanned = True

for idx, line in enumerate(out.splitlines()):
    if idx == 2:
        scanned = False


Imagine I have two PDF files:


scanned.pdf
notscanned.pdf


The results of above:

scanned.pdf:

name                                 type              encoding         emb sub uni object ID
------------------------------------ ----------------- ---------------- --- --- --- ---------


notscanned.pdf

name                                 type              encoding         emb sub uni object ID
------------------------------------ ----------------- ---------------- --- --- --- ---------
TNNLVN+Calibri                       TrueType          WinAnsi          yes yes yes      9  0


As you can see, the notscanned.pdf file contains font information.

In my Python script, I iterate over each line in the command line output:

for idx, line in enumerate(out.splitlines()):
    if idx == 2:
        scanned = False


And if there is a line 2, then it contains font information.

I am wondering if this approach is viable? I've been searching for a solution for quite a bit, and it seems there is no way to know 100%.
How about the PDF metadata check on '/Resources' ?! 

I believe for any text in a PDF (electronic document) there are more chances of having a font, especially the PDF, whose objective is to make a portable file, so, it maintains the font definition.

If you are a PyPDF2 user, try 

pdf_reader = PyPDF2.PdfFileReader(input_file_location)
page_data = pdf_reader.getPage(page_num)

if '/Font' in page_data['/Resources']:
    print("[Info]: Looks like there is text in the PDF, contains:", page_data['/Resources'].keys())
elif len(page_data1['/Resources'].get('/XObject', {})) != 1:
    print("[Info]: PDF Contains:", page_data['/Resources'].keys())

for obj in x_object:
    obj_ = x_object[obj]
    if obj_['/Subtype'] == '/Image':
        print("[Info]: PDF is image only")