如何使用Python将多页PDF转换为图像对象列表?

12

我想将一个多页的PDF文档转换成图像对象列表结构,而不保存在磁盘上(我想用PIL图像库进行处理),使用Python。到目前为止,我只能先将图像写入文件中:

from wand.image import Image

with Image(filename='source.pdf') as img:

    with img.convert('png') as converted:
        converted.save(filename='pyout/page.png')

但是我如何直接将上面的img对象转换为PIL.Image对象的列表?

4个回答

8

新答案:

使用pip安装pdf2image模块。

from pdf2image import convert_from_path, convert_from_bytes
images = convert_from_path('/path/to/my.pdf')

您可能也需要安装Pillow。这可能仅适用于Linux系统。

https://github.com/Belval/pdf2image

两种方法的结果可能会有所不同。

原回答:

Python 3.4:

from PIL import Image
from wand.image import Image as wimage
import os
import io

if __name__ == "__main__":
    filepath = "fill this in"
    assert os.path.exists(filepath)
    page_images = []
    with wimage(filename=filepath, resolution=200) as img:
        for page_wand_image_seq in img.sequence:
            page_wand_image = wimage(page_wand_image_seq)
            page_jpeg_bytes = page_wand_image.make_blob(format="jpeg")
            page_jpeg_data = io.BytesIO(page_jpeg_bytes)
            page_image = Image.open(page_jpeg_data)
            page_images.append(page_image)

最后,您可以调用mogrify系统调用,但这可能更加复杂,因为您需要管理临时文件。

我已经包含了@jtlz2建议的编辑,但由于它已被拒绝,我无法接受。基本上,将Image默认指向PIL.Image,而不是wand.image.Image,我认为后者很少使用。 - Bryant Kou
我的文件保存了吗?它在哪里? - Peter.k

5

使用PIL将图像文件保存并在读取后删除是一种简单的方法。

我建议使用pdf2image包。 在使用pdf2image包之前,您可能需要通过anaconda安装poppler包。

conda install -c conda-forge poppler

如果您遇到困难,请在安装之前更新 Conda:

conda update conda
conda update anaconda

安装 poppler 后,通过 pip 安装 pdf2image :
pip install pdf2image

然后执行这段代码:

from pdf2image import convert_from_path
dpi = 500 # dots per inch
pdf_file = 'work.pdf'
pages = convert_from_path(pdf_file ,dpi )
for i in range(len(pages)):
   page = pages[i]
   page.save('output_{}.jpg'.format(i), 'JPEG')

在此之后,请使用PIL阅读它们并删除它们。

1
我的使用魔杖的答案如下:
from wand.image import Image as wi
...
Data = filedialog.askopenfilename(initialdir="/", title="Choose File", filetypes = (("Portable Document Format","*.pdf"),("All Files", "*.*")))
apps.append(Data)
print(Data)
PDFfile = wi(filename = Data, resolution = 300)
Images = PDFfile.convert('tiff')
ImageSequence = 1
for img in PDFfile.sequence:
    image = wi(image = img)
    image.save(filename = "Document_300"+"_"+str(ImageSequence)+".tiff")
    ImageSequence += 1

希望这能帮到你。
我已经用图形用户界面实现了它,你只需要选择你的文件即可。
你也可以将PDFfile.convert()转换为jpg等格式。

-1

从这里https://blog.alivate.com.au/poppler-windows/下载Poppler,然后使用以下代码:

from pdf2image import convert_from_path

file_name = 'A019'
images = convert_from_path(r'D:\{}.pdf'.format(file_name), poppler_path=r'C:\poppler-0.68.0\bin')

for i, im in enumerate(images):
    im.save(r'D:\{}-{}.jpg'.format(file_name,i))


如果由于poppler路径而出现错误,请将poppler的bin路径添加到Windows环境变量的"Path"中。路径可以是这样的"C:\poppler-0.68.0\bin"。

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