PHP通过命令行调用Ghostscript把pdf转换成图片集
1.使用命令行在服务器上安装Ghostscript,网上教程很多按步骤操作就行。
2.使用php执行命令行。
/*** 使用Ghostscript命令行转换PDF为图片** @param string $pdfUrl PDF文件URL* @param string $folderName 存储目录名 (默认值:wenjianming)** @return array 包含状态和图像路径/错误信息的数组*/public function ghostscriptPdfToImages(string $pdfUrl, string $folderName = 'wenjianming'): array{$tempPdfPath = '';try {// 1. 准备目标路径$basePath = public_path() . "/pdf/{$folderName}";if (!is_dir($basePath)) {if (!mkdir($basePath, 0755, true)) {throw new \RuntimeException("无法创建目录: {$basePath}");}}// 2. 下载PDF文件$pdfContent = @file_get_contents($pdfUrl);if ($pdfContent === false) {throw new \RuntimeException("无法下载PDF文件: {$pdfUrl}");}$tempPdfPath = sys_get_temp_dir() . DIRECTORY_SEPARATOR . uniqid('pdf_') . '.pdf';if (!file_put_contents($tempPdfPath, $pdfContent)) {throw new \RuntimeException("无法保存临时PDF文件");}// 3. 使用Ghostscript命令获取PDF页数$pageCountCmd = "gs -q -dNODISPLAY -c \"({$tempPdfPath}) (r) file runpdfbegin pdfpagecount = quit\"";$totalPages = (int)trim(shell_exec($pageCountCmd));echo '获取页数成功:'.$totalPages . "页";if ($totalPages === 0) {throw new \RuntimeException("PDF 文件不包含有效页面");}// 4. 使用Ghostscript逐页转换PDF到图片,以控制内存使用echo '开始逐页转换PDF到图片...' ;for ($page = 1; $page <= $totalPages; $page++) {echo '正在处理第'.$page . "页";$imagePath = $basePath . '/' . $page . '.jpg';// 使用Ghostscript转换单页// -dNOPAUSE -dBATCH: 不暂停并在完成后退出// -dSAFER: 安全模式// -sDEVICE=jpeg: 输出为JPEG格式// -r150: 分辨率为150dpi (可根据需要调整)// -dJPEGQ=90: JPEG质量为90% (可根据需要调整)// -dFirstPage={$page} -dLastPage={$page}: 只处理指定页$gsCommand = "gs -dNOPAUSE -dBATCH -dSAFER -sDEVICE=jpeg -r150 -dJPEGQ=90 " ."-dFirstPage={$page} -dLastPage={$page} " ."-sOutputFile=\"{$imagePath}\" \"{$tempPdfPath}\"";$output = [];$returnCode = 0;exec($gsCommand, $output, $returnCode);if ($returnCode !== 0) {throw new \RuntimeException("处理第{$page}页时失败: " . implode("", $output));}// 每处理几页后暂停一下,给系统时间释放资源if ($page % 5 === 0) {echo '完成5页,暂停1秒...';sleep(1);echo '当前内存使用: ' . round(memory_get_usage(true) / 1024 / 1024, 2) . "MB";}echo '完成: ' . $imagePath ;}echo '所有页面转换完成';return ['success' => true,'image_count' => $totalPages,'basePath' => $basePath,];} catch (\Throwable $e) {return ['success' => false,'error' => $e->getMessage(),'error_detail' => '请确保已安装 Ghostscript'];} finally {// 确保清理临时文件if ($tempPdfPath && file_exists($tempPdfPath)) {@unlink($tempPdfPath);}}}
效率很高转的比php的pdf包快多了