How do I convert a PDF document to a preview image in PHP?


What libraries, extensions etc. would be required to render a portion of a PDF document to an image file?

Most PHP PDF libraries that I have found center around creating PDF documents, but is there a simple way to render a document to an image format suitable for web use?

Our environment is a LAMP stack.

3/7/2011 3:02:26 PM

Accepted Answer

You need ImageMagick and GhostScript

$im = new imagick('file.pdf[0]');
header('Content-Type: image/jpeg');
echo $im;

The [0] means page 1.

1/14/2019 11:29:37 AM

For those who don't have ImageMagick for whatever reason, GD functions will also work, in conjunction with GhostScript. Run the ghostscript command with exec() to convert a PDF to JPG, and manipulate the resulting file with imagecreatefromjpeg().

Run the ghostscript command:

exec('gs -dSAFER -dBATCH -sDEVICE=jpeg -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -r300 -sOutputFile=whatever.jpg input.pdf')

To manipulate, create a new placeholder image, $newimage = imagecreatetruecolor(...), and bring in the current image. $image = imagecreatefromjpeg('whatever.jpg'), and then you can use imagecopyresampled() to change the size, or any number of other built-in, non-imagemagick commands

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow