Search code examples
phpimagick

PDF to Images generate


I have PDF with 25 pages, I want to convert it into images with all pages.

My code:

First I have found number of pages.

$tmpfname= 'test_pdf.pdf';
$path = "/var/www/my_path";
$numberOfPages = $this->count_pages($tmpfname);
$numberOfPages = intval($numberOfPages); // Number of pages eg.25

Loop for convert pdf to images

for($i=0;$i<=$numberOfPages;$i++){
    $im = new imagick( $tmpfname.'['.$i.']' );
    $im->setCompression(Imagick::COMPRESSION_JPEG);
    $im->resizeImage('1024','800', Imagick::FILTER_UNDEFINED, 0.9, true);
    $im->setCompressionQuality(100);
    $im->setImageFormat('jpeg');
    $im->writeImage($path.'/'.$i.'.jpg');
    $im->clear(); 
    $im->destroy();
}

Function for find number of pages

function count_pages($pdfname) {
    $pdftext = file_get_contents($pdfname);
    $num = preg_match_all("/\/Page\W/",$pdftext, $dummy); 
    return $num;
}

PDF uploaded ok, and also converted images from PDF. But got this type of error after completed process:

Fatal error: Uncaught exception 'ImagickException' with message 
'Postscript delegate failed /var/www/php/flipbook/uploads/flipbooks/61/test_pdf.pdf': 
@ error/pdf.c/ReadPDFImage/663' in /var/www/php/flipbook/application/controllers/admin/flipbooks.php:83 
Stack trace: #0 /var/www/php/flipbook/application/controllers/admin/flipbooks.php(83): 
Imagick->__construct('/var/www/php/fl...') 
#1 [internal function]: Flipbooks->create() 
#2 /var/www/php/flipbook/system/core/CodeIgniter.php(359): call_user_func_array(Array, Array) 
#3 /var/www/php/flipbook/index.php(210): require_once('/var/www/php/fl...') 
#4 {main} thrown in /var/www/php/flipbook/application/controllers/admin/flipbooks.php on line 83

Any buddy can help me very appreciate...


Solution

  • I got the perfect solution from here

    My new code

    $tmpfname= 'test_pdf.pdf';
    $path = "/var/www/my_path";
    $numberOfPages = $this->count_pages($tmpfname);
    $numberOfPages = intval($numberOfPages); // Number of pages eg.25
    
    // Saving every page of a PDF separately as a JPG thumbnail
    $images = new Imagick("test_pdf.pdf");
    foreach($images as $i=>$image) {
       // Providing 0 forces thumbnail Image to maintain aspect ratio
       $image->thumbnailImage(1024,0);
       $image->writeImage($path.'/'.$i.'.jpg');
    }
    $images->clear();
    
    function count_pages($pdfname) {
        $pdftext = file_get_contents($pdfname);
        $num = preg_match_all("/\/Page\W/",$pdftext, $dummy); 
        return $num;
    }