Converting PDF to PNG with transparent background

Questions and postings pertaining to the usage of ImageMagick regardless of the interface. This includes the command-line utilities, as well as the C and C++ APIs. Usage questions are like "How do I use ImageMagick to create drop shadows?".
Post Reply
treybean
Posts: 1
Joined: 2012-06-24T06:54:41-07:00
Authentication code: 13

Converting PDF to PNG with transparent background

Post by treybean »

We have a Ruby on Rails application that needs to convert a PDF into a PNG with a transparent background. We're using rmagick 2.13.1. On our development machines the following code works exactly how we want it.

Code: Select all

pages = Magick::Image.from_blob(book.to_pdf.render){ self.density = 300 }
page = pages[0]

image_file = Tempfile.new(['preview_image', '.png'])
image_file.binmode
image_file.write( page.to_blob { |opt| opt.format = "PNG" } )
We thens save the image_file and all is peachy. When we deployed to a review server on Heroku, though, the generated image has a white background. It turns out that Heroku's cedar stack is using imagemagick ImageMagick 6.5.7-8 2010-12-02 where we're using ImageMagick 6.7.5-7 2012-05-08 on our development machines.

I've scoured the net, including this forum, for older posts that might apply to the older version to try and figure out how to generate the transparent PNGs. It's surely supported, but, so far I haven't been able to figure out the right combination of settings.

To verify that it wasn't the PDF generation that was the problem, I downloaded a PDF generated on Heroku and successfully converted it using the above code (slightly modified to read the file in instead of generate it) to a transparent PNG.

Some of the things I've tried in various combinations are:
So, the question is "is this possible?". If so, which settings do I need to set on the image before writing it out?

I'm also investigating including a compiled binary of a more up to date Imagemagick on Heroku.

Any help is appreciated.
User avatar
fmw42
Posts: 25562
Joined: 2007-07-02T17:14:51-07:00
Authentication code: 1152
Location: Sunnyvale, California, USA

Re: Converting PDF to PNG with transparent background

Post by fmw42 »

In command line one would use

convert image.pdf PNG32:image.png

though PNG32 should not be needed if the pdf has transparency.

The pdf/ps delegate device in your delegates.xml file can support multipage pdfs with NO transparency or a single pdf page with transparency. If you want transparency, then edit the file and set sDEVICE=pngalpha


<delegate decode="ps:alpha" stealth="True" command=""gs" -q -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 "-sDEVICE=pngalpha" -dTextAlphaBits=%u -dGraphicsAlphaBits=%u "-r%s" %s "-sOutputFile=%s" "-f%s" "-f%s""/>


If that is not your problem, then you will need to hear further from the IM developers as this is my best guess.
Post Reply