技术饭

通过ghostscript将pdf转成图片

copylian    0 评论    2035 浏览    2024.04.09

需要将pdf转成图片有很多种方式,对于php来说可以通过 ImageMagick 扩展来实现,ImageMagick 主要是处理一系列图片处理,但是如果需要支持pdf转图片需要用到 ghostscript 依赖来实现转换。


ImageMagick 文档解释:https://www.php.net/manual/en/imagick.requirements.php

ImageMagick >= 6.2.4 is required. The amount of file formats supported by Imagick depends entirely upon the amount of formats supported by your ImageMagick installation. For example, Imagemagick requires ghostscript to conduct PDF operations.


ImageMagick + ghostscript 的方式可以参考:https://www.copylian.com/technology/531.html


这次主要是直接是使用 ghostscript  命令来实现转换

ghostscript官网:https://www.ghostscript.com/


1、ubuntu安装 ghostscript  

apt update  # 更新软件包

apt install ghostscript  # 安装gs

gs -v  # 查看版本


2、命令执行测试,输出pdf内容:https://ghostscript.readthedocs.io/en/latest/Use.html#switches-for-pdf-files

gs -dSAFER -dBATCH -dNOPAUSE -r250 -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -sDEVICE=jpeg -sOutputFile=/images/%d.jpg /tmp/test.pdf

该命令是把/tmp/test.pdf转换成jpg文件,放在/images目录,前提是/images目录已经存在,不存在会报错,图片文件按数字命名%d


gs -sDEVICE=jpeg -sPageList=1 -sOutputFile=- -dBATCH -dNOPAUSE -dQUIET /tmp/test.pdf

该命令是把/tmp/test.pdf转换成jpg文件流


3、php使用 proc_open() 方法执行

// pdf to jpg
function pdfToJpg($pdf){

//  $pdf = 'https://test.com/a.pdf';

 
$filename = '/tmp/'.bin2hex(random_bytes(16)).'.pdf';

 file_put_contents($filename, file_get_contents_curl($pdf));

// You cannot work with PDF files from stdin, as the PDF format makes it more or less essential to be able to have random access to all parts of the file.
// In the cases where Ghostscript reads a PDF file from stdin it first copies it to a local file then works on that,
// so it isn't working from stdin anyway.
 
$process = proc_open(
   ['gs', '-sDEVICE=jpeg', '-sPageList=1', '-sOutputFile=-', '-dBATCH', '-dNOPAUSE', '-dQUIET', $filename],
   [1 => ['pipe','w']],
   $pipes
 
);

 try {
   $c = stream_get_contents($pipes[1]);
   fclose($pipes[1]);
 } finally {
   $code = proc_close($process);
   if ($code) {
     error_log('pdf转图片失败, code :'.$code);
   }
 }

 return $c;
}


pdfToJpg() 方法 输出装换后的图片文件流。

proc_open() 函数可参考:

https://www.copylian.com/technology/534.html

https://www.php.net/manual/zh/function.proc-open.php


只袄早~~~
感谢你的支持,我会继续努力!
扫码打赏,感谢您的支持!
ghostscript gs pdf 图片 

文明上网理性发言!

  • 还没有评论,沙发等你来抢