生成PDF到图像

时间:2014-05-31 13:14:18

标签: php imagick

我有25页的PDF,我想把它转换成所有页面的图像。

我的代码:

首先我找到了页数。

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

循环用于将pdf转换为图像

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 count_pages($pdfname) {
    $pdftext = file_get_contents($pdfname);
    $num = preg_match_all("/\/Page\W/",$pdftext, $dummy); 
    return $num;
}

PDF上传好了,还转换了PDF图片。但是在完成过程后出现了这种错误:

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

任何好友都可以帮助我... ...

2 个答案:

答案 0 :(得分:0)

如果没有别的,你有一个错误:

for($i=0;$i<=$numberOfPages;$i++){
//..
}

当索引从零开始时,这会尝试打印numberOfPages + 1个页面。

答案 1 :(得分:0)

我从here

获得了完美的解决方案

我的新代码

$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;
}