4

I'm developing a service in which I now need to extract images from a PDF file. From a Linux command line I can extract images using the Poppler library like this:

pdfimages my_file.pdf /tmp/image

Since I'm using the Python Flask framework and I want to run my service on Heroku I want to extract the images using pure Python (or any library that can run on Heroku in a Flask system).

So does anybody know how I can extract images from pdf in pure Python? I prefer open source solutions, but I'm willing to pay for it if needed (as long as it works under my own control on Heroku).

4

1 回答 1

0
import minecart
import os
from NumberOfPages import getPageNumber

def extractImages(filename):

# making new directory if it doesn't exist
new_dir_name = filename[:-4]
if not os.path.exists(new_dir_name):
    os.makedirs(new_dir_name + '/images')
    os.makedirs(new_dir_name + '/text')

# open the target file
pdf_file = open(filename, 'rb')

# parse the document through the minecart. Document function
doc = minecart.Document(pdf_file)

# getting the number of pages in the pdf file.
num_pages = getPageNumber(filename)

# getting the list of all the pages
page = doc.get_page(num_pages)

count = 0
for page in doc.iter_pages():
    for i in range(len(page.images)):
        try:
            im = page.images[i].as_pil()  # requires pillow
            name = new_dir_name + '/images/image_' + str(count) + '.jpg'
            count = count + 1
            im.save(name)
        except:
            print('Error encountered at %s' % filename)

doc_name = new_dir_name + '/images/info.txt'

with open(doc_name, 'a') as x:
        print( x.write('Number of images in document: {}'.format(count)))
于 2019-05-06T17:51:13.350 回答