5

I would like to use imagemagick Wand package to convert all pages of a pdf file into a single image file. I am having the following trouble though (see comments below which highlight problem)

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)

My end goal it to be able to specify which pages are to be converted to one continual image. This is possible from the command line with a bit of

convert -append input.pdf[0-4]

but I am trying to work with python.

I see we can get slices by doing this:

[x for x in w.sequence[0:1]] # get page 1 and 2

now its a question of how to join these pages together.

4

3 回答 3

11

我的解决方案:

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

它有效,并且与其他答案相比,它对于一些在不同页面中具有可变大小的多页 pdf 文件似乎更灵活。

于 2017-04-11T11:18:16.367 回答
10

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

我没有注意到任何内存链接问题,尽管我的 PDF 往往只有 2 或 3 页。

于 2014-10-07T10:19:54.023 回答
1

注意:这会导致内存泄漏

我找到了一个方法。可能有更好的方法,但它有效。

class Preview(object):
    def __init__(self, file):
        self.image = Image(file=file)

    def join_pages(self, page_count):
        canvas = self.create_canvas(page_count=page_count)
        for page_number in xrange(page_count):
            canvas.composite(
                self.image.sequence[page_number],
                top=self.image.height*page_number,
                left=0,
            )

    def create_canvas(self, page_count):
        return Image(
            width=self.pdf.width,
            height=self.image.height*page_count,
        )

    preview = Preview(open('path/to/pdf')
    preview.join_pages(3)
于 2014-05-17T09:28:18.493 回答