Python Wand convert PDF to PNG disable transparent (alpha_channel)

Munro picture Munro · Jan 7, 2015 · Viewed 34.3k times · Source

I'm trying to convert a PDF to PNG - this all works fine, however, the output image is still transparent even when I believe I have disabled it:

with Image(filename='sample.pdf', resolution=300) as img:
    img.background_color = Color("white")
    img.alpha_channel = False
    img.save(filename='image.png')

The above produces the images but are transparent, I also tried the below:

with Image(filename='sample.pdf', resolution=300, background=Color('white')) as img:
    img.alpha_channel = False
    img.save(filename='image.png')

which produces this error:

Traceback (most recent call last):
  File "file_convert.py", line 20, in <module>
    with Image(filename='sample.pdf', resolution=300, background=Color('white')) as img:
  File "/Users/Frank/.virtualenvs/wand/lib/python2.7/site-packages/wand/image.py", line 1943, in __init__
    raise TypeError("blank image parameters can't be used with image "
TypeError: blank image parameters can't be used with image opening parameters

Answer

Manuel Riel picture Manuel Riel · Mar 29, 2016

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

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