Saving Each PDF Page to an Image Using Imagick

Viewed 16293

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();
}
4 Answers
Related