如何使用ImageMagick for PHP将多页PDF转换为图像?

时间:2021-10-12 08:57:52

I want to convert the pdf file into images. I am using ImageMagick for image conversion in cakePHP.

我想将pdf文件转换为图像。我正在使用ImageMagick在cakePHP中进行图像转换。

When I take a PDF with a single page, its gets converted into image but the problem is when I take a PDF with multiple pages, then only the last page of the document is getting converted to image, instead of all pages.

当我用单个页面获取PDF时,它会转换为图像,但问题是当我拍摄多页的PDF时,只有文档的最后一页转换为图像而不是所有页面。

How can I fix this?

我怎样才能解决这个问题?

This is the code I have.

这是我的代码。

 public function convertToImage() {  
     $this->layout = "ajax";

        $uploadfile=APP.WEBROOT_DIR.DS.'files'.DS.$this->request->data['f'];
        $uploaddir=APP.WEBROOT_DIR.DS.'files'.DS.'images'.DS;
        $im = new imagick();
        $im->setResolution(80,80);
        $im->readimage($uploadfile);//."[0]");
        $im->setImageFormat('jpeg');
        $image_name = $this->request->data['f'].".jpg";
        $imageprops = $im->getImageGeometry();
        if ($imageprops['width'] <= 1275 && $imageprops['height'] <= 1650) {
            // don't upscale
         } else {
             $im->resizeImage(1275,1650, imagick::FILTER_LANCZOS, 0.9, true);
         }


        $im->writeImage($uploaddir .$image_name);
        $im->clear();
        $im->destroy();exit;
 }  

1 个解决方案

#1


You can access each page by

您可以访问每个页面

$im->readimage($uploadfile."[".$pageNumber."]");

With imagemagick you can also read how many pages there are in a pdf:

使用imagemagick,您还可以阅读pdf中有多少页面:

$document = new Imagick('document.pdf'); 
$document->getNumberImages();

With this number you can iterate over each page and save an image.

使用此编号,您可以遍历每个页面并保存图像。

As stated here: http://php.net/manual/en/class.imagick.php#111197 the pointer of imagemagick is set to the last page when used with pdfs.

如上所述:http://php.net/manual/en/class.imagick.php#111197与PDF格式一起使用时,imagemagick的指针设置为最后一页。

#1


You can access each page by

您可以访问每个页面

$im->readimage($uploadfile."[".$pageNumber."]");

With imagemagick you can also read how many pages there are in a pdf:

使用imagemagick,您还可以阅读pdf中有多少页面:

$document = new Imagick('document.pdf'); 
$document->getNumberImages();

With this number you can iterate over each page and save an image.

使用此编号,您可以遍历每个页面并保存图像。

As stated here: http://php.net/manual/en/class.imagick.php#111197 the pointer of imagemagick is set to the last page when used with pdfs.

如上所述:http://php.net/manual/en/class.imagick.php#111197与PDF格式一起使用时,imagemagick的指针设置为最后一页。