Saving Each PDF Page to an Image Using Imagick Saving Each PDF Page to an Image Using Imagick codeigniter codeigniter

Saving Each PDF Page to an Image Using Imagick


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.


 /* convert pdf file to list  image files */                if($_FILES['file_any']['type']=='application/pdf'){                    $file_name = str_replace(substr($url,0,strpos($url,$_FILES['file_any']['name'])),'',$url);                    $basename = substr($file_name,0,strpos($file_name,'.'));                    $abcd = wp_upload_dir();                    $delpath = $abcd['path'];                    $savepath = $abcd['url'];                    $dirpath = substr($savepath,(strpos($savepath,'/upl')+1));                    $file_name = basename($file_name, '.pdf');                    $img = new imagick($delpath.'/'.$file_name.'.pdf');                    $img->setImageBackgroundColor('white');                    $img->setResolution(300,300);                    $num_pages = $img->getNumberImages();                    $img->setImageCompressionQuality(100);                    $imageurl = NULL;                    $imagedelurl = NULL;                    for($i = 0;$i < $num_pages; $i++) {                                 $imageurl[]=$savepath.'/'.$basename.'-'.$i.'.jpg';                        $imagedelurl[] = $delpath.'/'.$basename.'-'.$i.'.jpg';                        // Set iterator postion                        $img->setIteratorIndex($i);                        // Set image format                        $img->setImageFormat('jpeg');                        // Write Images to temp 'upload' folder                             $img->writeImage($delpath.'/'.$file_name.'-'.$i.'.jpg');                    }                    $img->destroy();                }


There is a much easier way without the loop, just use $img->writeImages($filename,false); and it will make a file per PDF-page. As you said, if you flatten the image first, it only saves 1 page.