Coaxing a nice PNG out of a PDF

Using ImageMagick, it's easy to convert a PDF to a PNG. However, if you need the resulting PNG to be large and crisp, an extra trick is needed.

A PDF generally scales perfectly. That's because it's not like a photo, which gets blocky when magnified too much. It's more a like a set of instructions about lines to draw, fonts to use, etc., which can be used at any magnification. On a high-resolution monitor, my PDF's look terrific when displayed full screen.  Naturally, when I convert the PDF to a PNG I want it to look as good. But my early conversions were spectacularly bad.

(Some PDF's don't scale well, like the ones you get from scanning a document. They are basically photos of pages, and you can't go beyond the resolution you start with. It's easy to tell if you're in this situation:  open the PDF in a program like Adobe Reader and keep magnifying it. If you start seeing blocky pixels, then you've passed the limit resolution of any image based on that PDF.)

To figure out why my output PNG was so poor I added the -verbose flag to the Imagemagick convert command I was using:

convert -verbose inputfile.pdf  -resize 3840x2160 outputfile.png

Scanning the output, I saw "PDF 454x255=>3840x2157." No wonder the output looked terrible. Even though the PDF file has the information in it to produce a great 4K picture, it's only being told to output an image at the resolution of 454x255. By looking online I discovered the solution is to use the -density option. As I increased the required image density, the resolution of the image being extracted from the PDF improved. I found 700 was enough:

convert -verbose -density 700 inputfile.pdf  -resize 3840x2160 outputfile.png

Now the output read, "PDF 4409x2480=>3840x2160." And, indeed, the resulting PNG was lovely.

The PDF's I've been generating lately come from the Tikz drawing program. I was using the default units in creating my pictures. Since I wanted the output to have an aspect ratio of 16:9, as it is intended to be displayed full screen on a monitor, I made my x-units go to 16, and my y-units go to 9. Thus, the program thought it was producing an image 16 cm by 9 cm. And so it gave a low resolution output. While I could force it to do better using the -density option as above, I found I could do the same thing simply by scaling with Tikz. If I did the following:

\begin{tikzpicture}[scale=5]

...

\end{tikzpicture}

the resulting PDF had the resolution I required, but the fonts came out tiny in an ocean of white.

Leave a Reply

Your email address will not be published. Required fields are marked *