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

Mathew Byrne picture Mathew Byrne · Jan 22, 2009 · Viewed 252.1k times · Source

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.

Answer

Paolo Bergantino picture Paolo Bergantino · Jan 22, 2009

You need ImageMagick and GhostScript

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

The [0] means page 1.