The Web Blinders logo

Programming

How to generate thumbnails for PDF documents with relative paths using imagick and GhostScript?

In some cases when you supply relative paths to imagick,you might get error message like UnableToOpenBlob No such file or directory @ error/blob.c/OpenBlob or WriteBlob Failed @ error/png.c/MagickPNGErrorHandler etc. You will see a work around for these error messages in this article
A PHP function for generating thumbnails for PDF documents with relative paths using imagick and GhostScript
PHP function to generate thumbnails.

A PHP function for generating thumbnails for PDF documents with relative paths using imagick and GhostScript

Below function will generate thumbnails with out any errors.


<?php
/***
 * This function will generate a thumbnail in png format for a pdf document using
 * ImageMagick -  http://php.net/imagick
 * Ghostscript -  https://sourceforge.net/projects/ghostscript/
 * @param $source - string - relative path to the source pdf (for example : ./originals/lorem-ipsum.pdf ) 
 * @param $destination - string - relative path to the directory where you want to place the generated thumbnail (for example : './thumnails')
 * @param $fileName - string - file name of the  thumbnail with out extension (for example : pdfthumbdemo )
 * @param width - number - width of the thumbnail
 * @param height  - number - height of the thumbnail 
 */
function generateThumbnail($source, $destination, $fileName, $width, $height)
{
    try {
        $source = realpath($source);
        $destination = realpath($destination) . DIRECTORY_SEPARATOR . $fileName . ".png";
        $imagick = new Imagick();
        $imagick->readImage($source . "[0]");
        $imagick->thumbnailimage($width, $height);
        $imagick->setIteratorIndex(0);
        $imagick->writeImages($destination, false);
        $imagick->clear();
        $imagick->destroy();
        return true;
    } catch (Exception $e) {
        echo $e->getMessage();
        return false;
    }
}
/*
Usage - var_dump(generateThumbnail('./originals/lorem-ipsum.pdf','./thumbnails','pdfthumbdemo',500,500));
For a working example visit 
https://github.com/thewebblinders/php-generate-thumnails-for-pdf-documents/blob/master/README.md
*/
?>


    

For live testing - https://github.com/thewebblinders/php-generate-thumnails-for-pdf-documents

Use comments section for any queries.

Need developers ?

if so, send a message.

thewebblinders@gmail.com

More Programming from our blog

SEARCH FOR ARTICLES