簡體   English   中英

如何在純 Python 中從 PDF 中提取圖像?

[英]How to extract images from a PDF in pure Python?

我正在開發一項服務,我現在需要從 PDF 文件中提取圖像。 從 Linux 命令行,我可以使用Poppler 庫提取圖像,如下所示

pdfimages my_file.pdf /tmp/image

由於我使用的是 Python Flask 框架並且我想在 Heroku 上運行我的服務,因此我想使用純 Python(或可以在 Flask 系統中的 Heroku 上運行的任何庫)提取圖像。

那么有人知道我如何在純 Python 中從 pdf 中提取圖像嗎? 我更喜歡開源解決方案,但如果需要,我願意為此付費(只要它在我自己的控制下在 Heroku 上運行)。

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)))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM