使用 PHP 将 PDF 转换为 JPG 图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13600598/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 05:45:46  来源:igfitidea点击:

Convert PDF to JPG image with PHP

phppdfimagemagickjpeg

提问by tony2

I am using ImageMagik to try and convert the contents of a PDF to JPG, but keep getting an empty jpg. I have made sure the perms are 777 on everything for testing so I am a little lost how to continue.

我正在使用 ImageMagik 尝试将 PDF 的内容转换为 JPG,但一直得到一个空的 jpg。我已经确保所有测试的烫发都是 777,所以我有点不知道如何继续。

Here is the script I am running

这是我正在运行的脚本

<?php

    exec('convert testfile.pdf output.jpg', $output, $return_var);

?>

回答by Errol Fitzgerald

Try this.

尝试这个。

<?php
    $pdf = 'testfile.pdf';
    $save = 'output.jpg';

    exec('convert "'.$pdf.'" -colorspace RGB -resize 800 "'.$save.'"', $output, $return_var);

?>

回答by Nelson

Use the absolute path to the binary, like this:

使用二进制文件的绝对路径,如下所示:

exec('/usr/bin/convert testfile.pdf output.jpg', $output, $return_var);

But make sure your convertbinary is actually on /usr/binyou can check that out with the following command:

但是请确保您的convert二进制文件确实在/usr/bin您可以使用以下命令检查出来:

which convert

which convert

回答by silly

convert -normalize yourfile.pdf[0] yourdestination.jpg

回答by imal hasaranga perera

ImageMagick internally use GhostScript and Generally the conversion of ImageMagick is slow Comparing to Ghoastscript, so If you are only interested on getting convert pdf to images then Ghostscript gscommand is faster. below is an sample wrapper around Ghostscript which I wrote few days back.

ImageMagick 内部使用 GhostScript 并且通常 ImageMagick 的转换比 Ghoastscript 慢,所以如果您只对将 pdf 转换为图像感兴趣,那么 Ghostscriptgs命令会更快。下面是我几天前写的 Ghostscript 的示例包装器。

PDFLib-Php

PDFLib-PHP

$pdflib = new ImalH\PDFLib\PDFLib();
$pdflib->setPdfPath($pdf_file_path);
$pdflib->setOutputPath($folder_path_for_images);
$pdflib->setImageQuality(95);
$pdflib->setDPI(300);
$pdflib->setPageRange(1,$pdflib->getNumberOfPages());
$pdflib->convert();

回答by Adam Kozlowski

Here you have my solution. Use Imagick directly in your php code.

在这里你有我的解决方案。直接在您的 php 代码中使用 Imagick。

Convert all PDF pages to JPG

将所有 PDF 页面转换为 JPG

 // create Imagick object
 $imagick = new Imagick();
 // Reads image from PDF
 $imagick->readImage('file.pdf');
 // Writes an image
 $imagick->writeImages('converted.jpg', false);

Convert specific PDF page to JPG

将特定的 PDF 页面转换为 JPG

 // create Imagick object
 $imagick = new Imagick();
 // Read image from PDF
 $imagick->readImage('test.pdf[0]');
 // Writes an image
 $imagick->writeImages('converted_page_one.jpg');

Another way to deal with this problem is to use spatie/pdf-to-imagelibrary.

处理这个问题的另一种方法是使用spatie/pdf-to-image库。

Cheers!

干杯!