Python Wand convert PDF to PNG disable transparent (alpha_channel)

Solution 1:

I also had some PDFs to convert to PNG. This worked for me and seems simpler than compositing images, as shown above.:

from wand.image import Image
from wand.color import Color

all_pages = Image(blob=self.pdf)        # PDF will have several pages.
single_image = all_pages.sequence[0]    # Just work on first page
with Image(single_image) as i:
    i.format = 'png'
    i.background_color = Color('white') # Set white background.
    i.alpha_channel = 'remove'          # Remove transparency and replace with bg.

Reference: wand.image

Solution 2:

From a previous answer, try creating an empty image with a background color, then composite over.

from wand.image import Image
from wand.color import Color

with Image(filename="sample.pdf", resolution=300) as img:
  with Image(width=img.width, height=img.height, background=Color("white")) as bg:
    bg.composite(img,0,0)
    bg.save(filename="image.png")

Solution 3:

Compiling the other answers, here is the function I use to convert a PDF into pages:

import os
from wand.image import Image
from wand.color import Color


def convert_pdf(filename, output_path, resolution=150):
    """ Convert a PDF into images.

        All the pages will give a single png file with format:
        {pdf_filename}-{page_number}.png

        The function removes the alpha channel from the image and
        replace it with a white background.
    """
    all_pages = Image(filename=filename, resolution=resolution)
    for i, page in enumerate(all_pages.sequence):
        with Image(page) as img:
            img.format = 'png'
            img.background_color = Color('white')
            img.alpha_channel = 'remove'

            image_filename = os.path.splitext(os.path.basename(filename))[0]
            image_filename = '{}-{}.png'.format(image_filename, i)
            image_filename = os.path.join(output_path, image_filename)

            img.save(filename=image_filename)