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.


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 .


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


You can also get the page count using

$im->getNumberImages();

Then you can can create thumbs of all the pages using a loop, eg.

'file.pdf['.$x.']'
链接地址: http://www.djcxy.com/p/88534.html

上一篇: HTML为PDF高分辨率

下一篇: 如何将PDF文档转换为PHP中的预览图像?