【问题标题】:How to extract images from a PDF in pure Python?如何在纯 Python 中从 PDF 中提取图像?
【发布时间】:2015-01-27 00:54:11
【问题描述】:

我正在开发一项服务,现在我需要从 PDF 文件中提取图像。从 Linux 命令行中,我可以使用 Poppler library 提取图像,例如 this

pdfimages my_file.pdf /tmp/image

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

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

【问题讨论】:

标签: python image pdf heroku image-extraction


【解决方案1】:
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)))

【讨论】:

  • 虽然这可能是一个很好的答案,但缺乏解释。请提供一些解释,避免只使用代码作为答案
猜你喜欢
  • 2020-04-04
  • 2019-10-15
  • 2021-03-14
  • 1970-01-01
  • 1970-01-01
  • 2011-01-29
  • 2013-12-18
  • 2014-12-17
相关资源
最近更新 更多