Paul Chris Jones's coding blog
PHP
JS

Converting PDF to PNGs with imagemagick while keeping the white background

30th December 2023

I had a PDF and I wanted to convert the pages to PNGs. The backgrounds of the PNGs needed to be white.

First I tried:

convert input.pdf -density 300 -quality 100 output.png

This worked except the PNG backgrounds were transparent instead of white.

Next, I tried:

convert input.pdf -density 300 -quality 100 -background white -flatten output.png

Hilariously, this created just one image, an amalgam of all the pages in the PDF. I don't know who thought that would be useful. It seems the problem was -flatten, which turns all pages into one resulting in a single composite image.

Next, I tried:

convert input.pdf -density 300 -quality 100 -background white y-%04d.png

This worked except all the PNGs were now tiny for some reason. 585 pixels by 739 pixels. Whereas before I got a wonderful and generous 2438 pixels by 3075 pixels.

Next, I tried:

convert input.pdf -density 300 -background white -quality 100 output.png

But convert was unimpressed by the -background option and the PNG backgrounds were transparent again. I was back to the start.

I read this:

-background is a setting and does nothing by itself. It needs an operator to act upon it, such as -flatten, etc. see http://www.imagemagick.org/Usage/basics/#options

So next, I tried:

convert input.pdf -density 300 -background white -alpha remove -quality 100 output.png

This worked. My PDF file was now a beautiful set of PNG images.

Leave a comment