使用imagick实现把PDF转成图片

浏览:160 发布日期:2019/06/12 分类:功能实现 关键字: pdf,图片
pdf在线预览时,如果文件比较大,加载速度比较慢,如果将pdf文件转化为图片格式,然后拼接,然后展示到页面上就比较快。
环境:
参考:
1、https://www.cnblogs.com/jinxiblog/p/8053008.html
2、https://www.cnblogs.com/E1900/p/8399671.html
注意要配置环境变量,要安装Ghostscript
控制器:

public function _initialize(){
parent::_initialize();
$this->pimg_model = new PdfImgModel();
}

public function pdf_look(){
$file_path = htmlspecialchars($this->request->get('file_path'));
$info = $this->pimg_model->getInfo(['file_path'=>$file_path]);
if(!$info){
$pdf_url = $_SERVER['DOCUMENT_ROOT'].$file_path;
$path = $_SERVER['DOCUMENT_ROOT']."/public/uploads/pdf";
$s= $this->pdf2png($pdf_url,$path);
$img_list = '';
foreach ($s as $key => $value) {
$img_list[$key] = str_replace($_SERVER['DOCUMENT_ROOT'],'',$value);
}
$data['file_path']= str_replace($_SERVER['DOCUMENT_ROOT'],'',$pdf_url);
$data['images'] = json_encode($img_list);
$data['optdt'] = date('Y-m-d H:i:s');
$this->pimg_model->save($data);
}else{
$img_list = json_decode(htmlspecialchars_decode($info['images']));
}
$this->assign('img_list',$img_list);
return view($this->style.'common/tpl_pdf');
}


private function pdf2png($pdf,$path,$page=-1){
if(!extension_loaded('imagick'))
{
return false;
}
if(!file_exists($pdf))
{
return false;
}
$im = new \Imagick();
$im->setResolution(120,120);
$im->setCompressionQuality(100);
if($page==-1)
$im->readImage($pdf);
else
$im->readImage($pdf."[".$page."]");
foreach ($im as $Key => $Var)
{
$Var->setImageFormat('png');
$filename = $path."/". md5($Key.time()).'.png';
if($Var->writeImage($filename) == true)
{
$Return[] = $filename;
}
}
return $Return;
}

安装工具:
链接: https://pan.baidu.com/s/1umYpwJ4_GDtcY-K3dDVNXw 提取码: n6t4
评论( 相关
后面还有条评论,点击查看>>