Article : How-to: Create PDF preview images in PHP – Part 2
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:
exec('command line to run');
?>
So to run ImageMagick from the command line we do:
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
//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
//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
//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
//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
How-to: Create PDF preview images in PHP
Use the Canonical
Sizing Images Correctly – Part One
Creating One Time Download Links
CSS Image Rollovers