如何使用纯Python从PDF文件中提取图像?

4

我正在开发一个服务,现在需要从PDF文件中提取图像。我可以在Linux命令行中使用Poppler库来提取图像,就像这样

pdfimages my_file.pdf /tmp/image

因为我使用的是Python Flask框架,而且想在Heroku上运行我的服务,所以我想使用纯Python(或任何可以在Flask系统上运行的库)来提取图像。

那么有谁知道我如何在纯Python中从pdf中提取图像吗? 我更喜欢开源解决方案,但如果需要的话,我愿意付费(只要它可以在我自己控制的Heroku上运行)。


"Image" = 希望只有位图图像? - Jongware
2
解决方案:https://dev59.com/L3E85IYBdhLWcg3wnU0d - Sergey Shashkov
可能是[在Python中提取PDF中的图像而不进行重新采样的重复问题?](https://dev59.com/L3E85IYBdhLWcg3wnU0d) - Labo
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)))

5
虽然这可能是一个好的答案,但缺乏解释。请提供一些解释,避免仅使用代码作为答案。 - Joao Vitorino

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接