PDF image thumbnail using ImageMagick and PHP

After searching Google and SO I found this little code to create thumbnails of PDF documents using ImageMagick.

The problem for me is embedding it in my WordPress theme. I think I am stuck on the cache path that the script needs for temporary files.

I use it as described in the article:

<img src="http://localhost/multi/wp-content/themes/WPalchemy-theme/thumbPdf.php?pdf=http://localhost/multi/wp-content/uploads/2012/03/sample.pdf&size=200 />

which should be right (maybe ... but I guess I'm right to use the full url for the actual file) because when I click on that url, I am taken to a page that reads the following error:

Unable to read the file: tmp/http://localhost/multi/wp-content/uploads/2012/03/sample.pdf.png

Now the tmp is defined in the thumbpdf.php script file, but I'm confused as to what this value should be. Is it a URL or a path? Like timthumb.php, can I do it relative to the thumbPdf.PHP script file? (I tried. / Cache, which is a setting in timthumb, and was pretty sure there was a / cache folder at the root of my theme, to no avail). also, fyi I put the / tmp folder in my root and still get the same error.

So how do I set up tmp to do this?

http://stormwarestudios.com/articles/leverage-php-imagemagick-create-pdf-thumbnails/

function thumbPdf($pdf, $width)
{
    try
    {
        $tmp = 'tmp';
        $format = "png";
        $source = $pdf.'[0]';
        $dest = "$tmp/$pdf.$format";

        if (!file_exists($dest))
        {
            $exec = "convert -scale $width $source $dest";
            exec($exec);
        }

        $im = new Imagick($dest);
        header("Content-Type:".$im->getFormat());
        echo $im;
    }
    catch(Exception $e)
    {
        echo $e->getMessage();
    }
}

$file = $_GET['pdf'];
$size = $_GET['size'];
if ($file && $size)
{
    thumbPdf($file, $size);
}

      

I saw this answer: How to convert PDF document to preview image in PHP? and I'm going to go try further

+3


source to share


1 answer


The error tells you everything you need.

 Unable to read the file: tmp/http://localhost/multi/wp-content/uploads/2012/03/sample.pdf.png 

      

Script is currently trying to read a file from tmp / folder servers.



 $tmp = 'tmp';
 $format = "png";
 $source = $pdf.'[0]';
 //$dest = "$tmp/$pdf.$format";
 $dest = "$pdf.$format";

      

Remember this is not very good, someone might use the ImageMagic bug to accomplish very nasty things by providing your script with a garbled external pdf source. You should at least check if the image is from a permitted source such as a request coming from the same host.

The best way to work with ImageMagic is to always save the generated image and only generate a new image if the generated image doesn't exist. Some ImageMagic operations are quite heavy on large files, so you don't want to burden your server.

+1


source







All Articles