Saving Each PDF Page to an Image Using Imagick

Mike Barwick picture Mike Barwick · Dec 15, 2013 · Viewed 14.7k times · Source

I have the following php function below that's converting a local PDF file into images. In short, I want each PDF page to be converted to a separate image.

The function converts the PDF to an image - but only the last page. I want every page of the PDF to be converted to a image and numbered. Not just the last page of the PDF.

Currently, this function converts the last page of example.pdf to example-0.jpg. Issue I'm sure lies within the for method. What am I missing?

$file_name = 'example.pdf'; // using just for this example, I pull $file_name from another function

function _create_preview_images($file_name) {

    // Strip document extension
    $file_name = basename($file_name, '.pdf');

    // Convert this document
    // Each page to single image
    $img = new imagick('uploads/'.$file_name.'.pdf');

    // Set background color and flatten
    // Prevents black background on objects with transparency
    $img->setImageBackgroundColor('white');
    $img = $img->flattenImages();

    // Set image resolution
    // Determine num of pages
    $img->setResolution(300,300);
    $num_pages = $img->getNumberImages();

    // Compress Image Quality
    $img->setImageCompressionQuality(100);

    // Convert PDF pages to images
    for($i = 0;$i < $num_pages; $i++) {         

        // Set iterator postion
        $img->setIteratorIndex($i);

        // Set image format
        $img->setImageFormat('jpeg');

        // Write Images to temp 'upload' folder     
        $img->writeImage('uploads/'.$file_name.'-'.$i.'.jpg');
    }

    $img->destroy();
}

Answer

Mike Barwick picture Mike Barwick · Dec 15, 2013

Seems like most of my code was correct. The issue was, I was using $img->flattenImages(); incorrectly. This merges a sequence of images into one image. Much like how Photoshop flattens all visible layers into an image when exporting a jpg.

I removed the above line and the individual files were written as expected.