Martin
Martin

Reputation: 6687

How to append pages of a pdf to a png in python with imagemagick

I'd like to convert a multipage PDF to a single PNG, which can be achieved via the CLI with convert in.pdf -append out%d.png per Convert multipage PDF to a single image.

Can I achieve the same in Python without shelling out? I currently have:

with Image(filename=pdf_file_path, resolution=150) as img:
    img.background_color = Color("white")
    img.alpha_channel = 'remove'
    img.save(filename=pdf_file_path[:-3] + "png")

Upvotes: 0

Views: 601

Answers (1)

emcconville
emcconville

Reputation: 24419

I can't remember if MagickAppendImage has been ported to , but you should be able to leverage wand.image.Image.composite.

from wand.image import Image

with Image(filename=pdf_file_path) as pdf:
    page_index = 0
    height = pdf.height
    with Image(width=pdf.width,
               height=len(pdf.sequence)*height) as png:
        for page in pdf.sequence:
            png.composite(page, 0, page_index * height)
            page_index += 1
        png.save(filename=pdf_file_path[:-3] + "png")

Upvotes: 1

Related Questions