Accessibility Navigation

ImageXY

ImageXY - Mac OS X Batch Photo Resizer

Checkout ImageXY - Painless image resizing for Mac OS X.

Quickly and painlessly bulk resize images, change image formats and create web-friendly photos for your website.

Available on the Mac App Store!

How-to: Create PDF preview images in PHP

A few months ago I was looking to create screenshots of PDF documents on the fly so that a preview could be shown to users of a website before downloading or opening the file.

The solution to my problem was simple…so simple in fact that I can’t believe I haven’t done it before.

This works on all the major OS’s – Windows, linux and Mac – you will just have to download and install the correct packages for the machine you want to run it on. Mac users may find it easier to use a package management tool such as Fink to handle the installation.

Install GhostScript

Download and install GhostScript which is an interpreter for PostScript and PDF. If your installing on a Linux machine it is likely that you will already have this installed, so check before hand.

Install ImageMagick

Download and install ImageMagick which is an fully feature laden image manipulation suite which we will use to convert the PDF. Again if your running Linux you may already have this installed – so double check and/or upgrade.

ImageMagick is an amazing tool and can handle pretty much anything you could think of doing to an image, and it’s fully command line based so you can use it on the fly from within your scripts.

The PHP Code

The PHP code that we will use to convert the PDF to a png will make use of the ImageMagick software that we just installed and call it from within the PHP script using the exec() function.

exec('convert "document.pdf" -colorspace RGB -geometry 200 "document.png"');

This line will convert the whole PDF document into individual images for each page at 200px wide. To just create an image of the first page of the PDF we use the following:

exec('convert "document.pdf[0]" -colorspace RGB -geometry 200 "document.png"');

To get the second page you would just replace ‘[0]’ with ‘[1]’ etc.

For more options check out the ImageMagick help pages or simply run ‘convert’ from the command line and play about with the options.

If your not a fan of PNG’s then simply change the extension to your favorite image type and it will output the screenshot in that format.

The Result

Example of PDF preview using PHP   Example of PDF preview using PHP

UPDATE: There is an updated version of this post here.


About The Author

Jacob Wyke is a web developer from the UK who makes complex things simple on the internet. He develops a batch image resizer for Mac OS X called ImageXY which you should try if you ever need to resize anything for the web.

You should also follow him on twitter.