imagemagick wand save pdf pages as images

痴心易碎 提交于 2019-12-05 19:25:50

A slight simplification of @rikAtee's answer / addition of detecting the page count automatically by counting the length of the sequence:

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

I haven't noticed any memory link issues, although my PDFs only tend to be 2 or 3 pages.

My solution:

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

It works, and compared to other answers, it appears more flexible to some multi-page pdf files with variable size in different pages.

note: this causes memory leak

I found a way. There is probably a better way, but it works.

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!