Download and install right version of ghostscript. In my case my PHP was x86 architecture, so I download Ghostscript 9.14 for Windows (32 bit)
.
Check, is imagick
extension available and loaded.
This line should be present in your php.ini
:
extension=php_imagick.dll
Also, check php_imagick.dll
in PHP's ext
directory.
<?php
function genPdfThumbnail($source, $target)
{
//$source = realpath($source);
$target = dirname($source).DIRECTORY_SEPARATOR.$target;
$im = new Imagick($source."[0]"); // 0-first page, 1-second page
$im->setImageColorspace(255); // prevent image colors from inverting
$im->setimageformat("jpeg");
$im->thumbnailimage(160, 120); // width and height
$im->writeimage($target);
$im->clear();
$im->destroy();
}
Call that function:
<?php
genPdfThumbnail('/uploads/my.pdf','my.jpg'); // generates /uploads/my.jpg
2019-04-09 adaptation from https://gist.github.com/umidjons/11037635
added error capture when a source is not a pdf or not a file path, else function outputs the new file path.
added optional size and page number, defaults to 256 pix made from first page in the pdf.
added page orentation and relative resize of height vs width as whatever is smaller than the maximum given size.
added the option of putting the output jpeg into a sub folder, auto creating directory if not already existent.
added correction of black zones on transparency in a pdf.
to call my version of the function implement it for example like this:
$pdf_thumb = genPdfThumbnail('/nfs/vsp/servername/u/username/public_html/any.pdf','thumbs/any.jpg')
to get page 2 as 150 pixel jpeg implement it for example as below.
however if the pdf does not have more than 1 page, be assured errors will occur.
$pdf_thumb = genPdfThumbnail('/nfs/vsp/servername/u/username/public_html/any.pdf','any_p02.pdf.jpeg',150,'02')
to see the result from the function thereafter implement this:
if($pdf_thumb){ echo $pdf_thumb; }else{ echo 'pdf source error'; }
the function itself: