Search code examples
phppdfimage-processingimagemagickimagick

PDF to JPG Imagic page selection


Loads of answers on how to do it for a command line

convert /path/to/file/file.pdf[3] output.jpg

great... but what if I am using in memory processing, I am generating PDF with PDFlib and then output its buffer to a function that I want to generate jpg preview of selected page. How? My code :

    [...]
    $buf = $pdf->get_buffer();

    //$buff is just a PDF stored in a string now.

    $im = new Imagick();
    $im->readimageblob($buf);

    $im->setImageFormat("jpg");
    $im->setimagecompressionquality(60);

    $len = strlen($im);
    header("Content-type: image/jpeg");
    header("Content-Length: $len");      
    header("Content-Disposition: inline; filename=test.jpg");

    echo $im;

This creates a jpeg but always returns last page of the PDF. I want to be able to choose which one will be converted. Is it doable without saving temporary files and using command line (exec('convert /path/to/file/file.pdf[3] output.jpg')) syntax?

Let me add that I tried

    $im->readimageblob($buf[2]);

and it did not work :)


Solution

  • It's not good news unfortunately, but I can definitively say that, as of time of writing, the ImageMagick (and PHP libraries) don't support the page notation that you're trying to use. (For people from the future finding this: I'm checking php-imagick-3.0.1 and imagemagick-6.6.0.4).

    I'm trying to do the exact same thing as you, and I've just spent the last few hours trawling through the source, trying to figure out what it does and how it gets the pages, and it looks like it simply won't use it when reading from a stream (ie. the readBlob() call).

    As such, I'm just going to be putting it in a temporary file and reading it from there instead. Not as elegant, but it'll work.