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包快多了