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 – Part 2

There were comments on the original part of this example expressing that it wasn’t very newbie friendly since I didn’t show much code and focussed mostly on the installation of ImageMagick and not what to do once you have it installed. This post will hopefully make it clearer for all those wanting to write the code to create the PDF previews.

The Problem

Users upload PDF’s to our websites and we want to show a preview or the whole PDF content in image form.

Requirements

The following applications need to be installed on the server you are running your webserver.
ImageMagick
GhostScript

The Code

To create the images of the PDF we call the external ImageMagick application from the command line. In PHP this is done like so:

<?php
	exec('command line to run');
?>

So to run ImageMagick from the command line we do:

<?php
	exec('/path/to/imagemagick');
?>

The paramters we then use to call ImageMagick depend on what we want to do, and consulting the ImageMagick help pages are the best way to learn exactly what is happening.

Below are some common examples:

Create GIF Thumbnail of First PDF Page

<?php
	//the path to the PDF file
	$strPDF = "my_pdf.pdf";
	exec("convert \"{$strPDF}[0]\" -colorspace RGB -geometry 200 \"output.gif\"");
?>

Create JPEG Thumbnails of ALL Pages Within PDF

<?php
	//the path to the PDF file
	$strPDF = "my_pdf.pdf";
	exec("convert \"{$strPDF}\" -colorspace RGB -geometry 200 \"output.jpg\"");
?>

Create Large PNG 1024px Image of First PDF Page

<?php
	//the path to the PDF file
	$strPDF = "my_pdf.pdf";
	exec("convert \"{$strPDF}[0]\" -colorspace RGB -geometry 1024 \"output.png\"");
?>

Create Large PNG 1024px Images of ALL Pages Within PDF

<?php
	//the path to the PDF file
	$strPDF = "my_pdf.pdf";	
	exec("convert \"{$strPDF}\" -colorspace RGB -geometry 1024 \"output.png\"");
?>

As you can see the code is very simple as we are just calling an external command line application to do the hard work – the only thing we have to do is provide the parameters to tell ImageMagick what to do.

This was a follow-up to How-to: Create PDF preview images in PHP


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.