PdfMerger.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. <?php
  2. namespace App\Services;
  3. use Illuminate\Support\Facades\Log;
  4. use Illuminate\Support\Facades\Process;
  5. use Illuminate\Support\Str;
  6. /**
  7. * PDF合并工具类
  8. * 支持pdfunite(生产环境)和qpdf(本地开发)
  9. */
  10. class PdfMerger
  11. {
  12. private string $mergeTool;
  13. private bool $isProduction;
  14. public function __construct()
  15. {
  16. $this->isProduction = app()->environment('production');
  17. $this->mergeTool = $this->detectMergeTool();
  18. }
  19. /**
  20. * 检测系统中可用的PDF合并工具
  21. */
  22. private function detectMergeTool(): string
  23. {
  24. // 生产环境优先使用pdfunite
  25. if ($this->isProduction) {
  26. if ($this->commandExists('pdfunite')) {
  27. return 'pdfunite';
  28. }
  29. }
  30. // 本地开发环境使用qpdf
  31. if ($this->commandExists('qpdf')) {
  32. return 'qpdf';
  33. }
  34. // 备选:尝试pdfunite
  35. if ($this->commandExists('pdfunite')) {
  36. return 'pdfunite';
  37. }
  38. throw new \Exception('未找到可用的PDF合并工具(pdfunite或qpdf)');
  39. }
  40. /**
  41. * 检查命令是否存在
  42. */
  43. private function commandExists(string $command): bool
  44. {
  45. // 【修复】异步环境中PATH可能不完整,尝试绝对路径
  46. $fullPaths = [
  47. // 本地开发路径
  48. "/opt/homebrew/bin/{$command}",
  49. "/usr/local/bin/{$command}",
  50. // 系统路径
  51. "/usr/bin/{$command}",
  52. "/usr/sbin/{$command}",
  53. // Docker/Laravel 容器常见路径
  54. "/bin/{$command}",
  55. "/sbin/{$command}",
  56. "/usr/local/sbin/{$command}",
  57. ];
  58. Log::debug("检查命令是否存在: {$command}", [
  59. 'checking_absolute_paths' => $fullPaths
  60. ]);
  61. // 首先尝试绝对路径
  62. foreach ($fullPaths as $path) {
  63. if (file_exists($path) && is_executable($path)) {
  64. Log::debug("找到命令(绝对路径): {$command} -> {$path}");
  65. return true;
  66. }
  67. }
  68. // 如果绝对路径都不行,再尝试which命令
  69. Log::debug("绝对路径未找到,尝试which命令: {$command}");
  70. $output = Process::run("which {$command}");
  71. $result = $output->successful();
  72. Log::debug("which命令结果", [
  73. 'command' => $command,
  74. 'successful' => $result,
  75. 'output' => $output->output(),
  76. 'error' => $output->errorOutput()
  77. ]);
  78. return $result;
  79. }
  80. /**
  81. * 合并多个PDF文件
  82. *
  83. * @param array $pdfPaths PDF文件路径数组
  84. * @param string $outputPath 输出文件路径
  85. * @return bool 合并是否成功
  86. * @throws \Exception
  87. */
  88. public function merge(array $pdfPaths, string $outputPath): bool
  89. {
  90. // 验证输入文件
  91. foreach ($pdfPaths as $path) {
  92. if (!file_exists($path)) {
  93. throw new \Exception("PDF文件不存在: {$path}");
  94. }
  95. }
  96. // 确保输出目录存在
  97. $outputDir = dirname($outputPath);
  98. if (!is_dir($outputDir)) {
  99. mkdir($outputDir, 0755, true);
  100. }
  101. Log::info('开始合并PDF', [
  102. 'tool' => $this->mergeTool,
  103. 'input_count' => count($pdfPaths),
  104. 'output_path' => $outputPath
  105. ]);
  106. try {
  107. switch ($this->mergeTool) {
  108. case 'pdfunite':
  109. return $this->mergeWithPdfunite($pdfPaths, $outputPath, null);
  110. case 'qpdf':
  111. return $this->mergeWithQpdf($pdfPaths, $outputPath, null);
  112. default:
  113. throw new \Exception("不支持的合并工具: {$this->mergeTool}");
  114. }
  115. } catch (\Exception $e) {
  116. Log::error('PDF合并失败', [
  117. 'tool' => $this->mergeTool,
  118. 'error' => $e->getMessage(),
  119. 'trace' => $e->getTraceAsString()
  120. ]);
  121. throw $e;
  122. }
  123. }
  124. /**
  125. * 获取当前使用的合并工具
  126. */
  127. public function getMergeTool(): string
  128. {
  129. return $this->mergeTool;
  130. }
  131. /**
  132. * 检查环境是否支持PDF合并
  133. */
  134. public function isSupported(): bool
  135. {
  136. return in_array($this->mergeTool, ['pdfunite', 'qpdf']);
  137. }
  138. /**
  139. * 【新增】快速合并模式(带进度回调)
  140. *
  141. * @param array $pdfPaths PDF文件路径数组
  142. * @param string $outputPath 输出文件路径
  143. * @param callable|null $progressCallback 进度回调函数 (percentage, message) => void
  144. * @return bool 合并是否成功
  145. * @throws \Exception
  146. */
  147. public function mergeWithProgress(array $pdfPaths, string $outputPath, ?callable $progressCallback = null): bool
  148. {
  149. // 进度回调:开始
  150. if ($progressCallback) {
  151. $progressCallback(0, '开始合并PDF...');
  152. }
  153. // 验证输入文件
  154. foreach ($pdfPaths as $index => $path) {
  155. if (!file_exists($path)) {
  156. throw new \Exception("PDF文件不存在: {$path}");
  157. }
  158. // 进度回调:验证文件
  159. if ($progressCallback) {
  160. $progress = round(($index + 1) / (count($pdfPaths) + 1) * 20, 0); // 前20%用于验证
  161. $progressCallback($progress, "验证PDF文件: " . basename($path));
  162. }
  163. }
  164. // 确保输出目录存在
  165. $outputDir = dirname($outputPath);
  166. if (!is_dir($outputDir)) {
  167. mkdir($outputDir, 0755, true);
  168. }
  169. Log::info('开始快速合并PDF', [
  170. 'tool' => $this->mergeTool,
  171. 'input_count' => count($pdfPaths),
  172. 'output_path' => $outputPath
  173. ]);
  174. try {
  175. // 进度回调:开始合并
  176. if ($progressCallback) {
  177. $progressCallback(20, "使用 {$this->mergeTool} 开始合并PDF...");
  178. }
  179. switch ($this->mergeTool) {
  180. case 'pdfunite':
  181. $result = $this->mergeWithPdfunite($pdfPaths, $outputPath, $progressCallback);
  182. break;
  183. case 'qpdf':
  184. $result = $this->mergeWithQpdf($pdfPaths, $outputPath, $progressCallback);
  185. break;
  186. default:
  187. throw new \Exception("不支持的合并工具: {$this->mergeTool}");
  188. }
  189. // 进度回调:完成
  190. if ($progressCallback) {
  191. $progressCallback(100, 'PDF合并完成!');
  192. }
  193. return $result;
  194. } catch (\Exception $e) {
  195. Log::error('PDF合并失败', [
  196. 'tool' => $this->mergeTool,
  197. 'error' => $e->getMessage(),
  198. 'trace' => $e->getTraceAsString()
  199. ]);
  200. if ($progressCallback) {
  201. $progressCallback(-1, 'PDF合并失败: ' . $e->getMessage());
  202. }
  203. throw $e;
  204. }
  205. }
  206. /**
  207. * 使用pdfunite合并PDF(带进度回调)
  208. * 【优化】添加进度反馈
  209. */
  210. private function mergeWithPdfunite(array $pdfPaths, string $outputPath, ?callable $progressCallback = null): bool
  211. {
  212. $command = 'pdfunite ' . implode(' ', array_map('escapeshellarg', $pdfPaths)) . ' ' . escapeshellarg($outputPath);
  213. Log::debug('执行pdfunite命令', ['command' => $command]);
  214. // 【优化】设置超时时间为60秒,避免无限等待
  215. $timeout = 60;
  216. if ($progressCallback) {
  217. $progressCallback(30, '执行pdfunite命令...');
  218. }
  219. $startTime = microtime(true);
  220. $output = Process::timeout($timeout)->run($command);
  221. $duration = round((microtime(true) - $startTime) * 1000, 2);
  222. if ($progressCallback) {
  223. $progressCallback(80, '处理PDF合并结果...');
  224. }
  225. if ($output->successful()) {
  226. Log::info('pdfunite合并成功', [
  227. 'output_path' => $outputPath,
  228. 'duration_ms' => $duration,
  229. 'file_count' => count($pdfPaths)
  230. ]);
  231. if ($progressCallback) {
  232. $progressCallback(95, "合并完成!耗时 {$duration}ms");
  233. }
  234. return true;
  235. }
  236. Log::error('pdfunite合并失败', [
  237. 'exit_code' => $output->exitCode(),
  238. 'output' => $output->output(),
  239. 'error' => $output->errorOutput(),
  240. 'duration_ms' => $duration,
  241. 'timeout_seconds' => $timeout
  242. ]);
  243. return false;
  244. }
  245. /**
  246. * 使用qpdf合并PDF(带进度回调)
  247. * 【修复】qpdf命令格式不正确,缺少页面范围参数
  248. * 正确格式:qpdf --empty --pages file1.pdf 1-z,file2.pdf 1-z -- output.pdf
  249. */
  250. private function mergeWithQpdf(array $pdfPaths, string $outputPath, ?callable $progressCallback = null): bool
  251. {
  252. // 【修复】构建正确的qpdf命令
  253. // qpdf --empty --pages file1.pdf 1-z,file2.pdf 1-z -- output.pdf
  254. // 每个文件都需要指定页面范围(1-z表示从第一页到最后一页)
  255. $pagesArgs = [];
  256. foreach ($pdfPaths as $pdfPath) {
  257. $pagesArgs[] = escapeshellarg($pdfPath) . ' 1-z';
  258. }
  259. $pagesArg = implode(',', $pagesArgs);
  260. $command = "qpdf --empty --pages {$pagesArg} -- -- " . escapeshellarg($outputPath);
  261. Log::debug('执行qpdf命令', ['command' => $command]);
  262. // 【优化】设置超时时间为60秒,避免无限等待
  263. $timeout = 60;
  264. if ($progressCallback) {
  265. $progressCallback(30, '执行qpdf命令...');
  266. }
  267. $startTime = microtime(true);
  268. $output = Process::timeout($timeout)->run($command);
  269. $duration = round((microtime(true) - $startTime) * 1000, 2);
  270. if ($progressCallback) {
  271. $progressCallback(80, '处理PDF合并结果...');
  272. }
  273. if ($output->successful()) {
  274. Log::info('qpdf合并成功', [
  275. 'output_path' => $outputPath,
  276. 'duration_ms' => $duration,
  277. 'file_count' => count($pdfPaths)
  278. ]);
  279. if ($progressCallback) {
  280. $progressCallback(95, "合并完成!耗时 {$duration}ms");
  281. }
  282. return true;
  283. }
  284. Log::error('qpdf合并失败', [
  285. 'exit_code' => $output->exitCode(),
  286. 'output' => $output->output(),
  287. 'error' => $output->errorOutput(),
  288. 'duration_ms' => $duration,
  289. 'timeout_seconds' => $timeout,
  290. 'corrected_command' => $command // 记录修正后的命令用于调试
  291. ]);
  292. return false;
  293. }
  294. }