imagemagick魔杖将pdf页面保存为图像

ric*_*ier 3 python pdf imagemagick imagemagick-convert wand

我想使用imagemagick Wand包将pdf文件的所有页面转换为单个图像文件.我有以下麻烦(见下面的评论突出问题)

import tempfile
from wand.image import Image


with file('my_pdf_with_5_pages.png') as f:
    image = Image(file=f, format='png')
    save_using_filename(image)
    save_using_file(image)

def save_using_filename(image):
    with tempfile.NamedTemporaryFile() as temp:
        # this saves all pages, but a file for each page (so 3 files)
        image.save(filename=temp.name)

def save_using_file(image):
    with tempfile.NamedTemporaryFile() as temp:
        # this only saves the first page as an image
        image.save(file=temp)
Run Code Online (Sandbox Code Playgroud)

我的最终目标是能够指定将哪些页面转换为一个连续图像.这可以从命令行中获得一些

convert -append input.pdf[0-4]
Run Code Online (Sandbox Code Playgroud)

但我正在尝试使用python.

我看到我们可以通过这样做得到切片:

[x for x in w.sequence[0:1]] # get page 1 and 2
Run Code Online (Sandbox Code Playgroud)

现在是一个如何将这些页面连接在一起的问题.

Ste*_*eve 8

稍微简化了@ rikAtee通过计算序列长度自动检测页数的答案/补充:

def convert_pdf_to_png(blob):
    pdf = Image(blob=blob)

    pages = len(pdf.sequence)

    image = Image(
        width=pdf.width,
        height=pdf.height * pages
    )

    for i in xrange(pages):
        image.composite(
            pdf.sequence[i],
            top=pdf.height * i,
            left=0
        )

    return image.make_blob('png')
Run Code Online (Sandbox Code Playgroud)

我没有注意到任何内存链接问题,虽然我的PDF只有2或3页.


小智 8

我的解决方案

from wand.image import Image

diag='yourpdf.pdf'

with(Image(filename=diag,resolution=200)) as source:
    images=source.sequence
    pages=len(images)
    for i in range(pages):
        Image(images[i]).save(filename=str(i)+'.png')
Run Code Online (Sandbox Code Playgroud)

它可以工作,并且与其他答案相比,对于在不同页面中具有可变大小的一些多页pdf文件,它看起来更灵活.