user1107888
user1107888

Reputation: 1525

Converting PDF to image with ImageMagick

I want to convert a downloded pdf file to an image via PHP. For this purpose, I am using Imagemagick extension for PHP. The problem is that if I download the pdf file via file_get_contents function, I cannot create a Imagemagic object with this downloaded content. Here is the code:

<?php

$url = "pdf webaddress";
$pdfData = file_get_contents($url);

try
    {

        $img = new Imagick($pdfData);
        $img->setResolution(480,640);
        $img->setImageFormat("jpeg");
        $img->writeImage("test.jpeg");  

    }
catch(Exception $e)
{
    echo $e->getMessage();
}
?>

I am getting the following error:

Unable to read the file: %PDF-1.6 %גדֿ׃ 7 0 obj <> endobj 86 0 obj <>/Filter/FlateDecode/ID[]/Index[7 146]/Info 6 0 R/Length 257/Prev 592751/Root 8 0 R/Size 153/Type/XRef/W[1 3 1]>>stream h�bbd`bׁ‘6 ’9DעƒH

Now, if I read in the locally stored pdf file, everything works fine. The code is:

 $image = "output.png";
 $img = new Imagick("path to pdf file");
 $img->setResolution(480,640);
 $img->setImageFormat("jpeg");
 $img->writeImage("test.jpeg"); 

Any suggestions, help is appreciated.

Upvotes: 1

Views: 5951

Answers (1)

strnk
strnk

Reputation: 2063

From the ImageMagick PHP extension documentation page, the Imagick constructor needs a filename parameters which can either be a local file or a URL. :

Paths can include wildcards for file names, or can be URLs.

You should pass the URL directly, without file_get_contents, PHP file streams are pretty powerful.

An other solution for you would be to store the file locally (see tempnam() and file_put_contents), but if you don't use it for anything else than converting it to an image it's pretty useless :

$pdfUrl = "...";
$tmpFileName = tempnam(sys_get_temp_dir(), "pdf");
file_put_contents($tmpFileName, file_get_contents($pdfUrl));
// Do your ImageMagick job
unlink($tmpFileName);

Upvotes: 3

Related Questions