在 PHP 中使用 Ghostscript 合并多个 PDF 文件

Ghostscript 是一个没有内置在 Windows 上的命令行库。首先,我们需要从链接 https://ghostscript.com/releases/gsdnld.html 安装 Ghostscript。
根据你的操作系统版本下载 Ghostscript 文件。该文件将是这样的:
gs9550w64.exe
运行下载的文件并安装它。安装完成后,转到安装目录的 bin 文件夹并将文件 gswin64c.exe 重命名为 gs.exe 以使用 gs 作为命令。
Ghostscript 的安装完成。下一步是使用 PHP 将 pdf 文件与 Ghostscript 合并。

点击查看代码
<?php
$files= array("one.pdf","two.pdf","three.pdf");
$pdfdir = "C:/Apache24/htdocs/samplepdfs/";
//we gave absolute path because sometimes the libraries can't detect the path. Please use your path here.
$output = $pdfdir."NewMergedPDF.pdf";
$cmd = "gs -dNOPAUSE -sDEVICE=pdfwrite -sOUTPUTFILE=".$output." -dBATCH ";
//setting enviroment variable path
putenv('PATH=C:\Program Files\gs\gs9.55.0\bin');

foreach($files as $file) {
    //Setting path for each file
    $pdf= $pdfdir.$file;
    //adding each file to the command
    $cmd = $cmd.$pdf." ";
}
// The final command will be the comment below, if you run this command directly in cmd, the output will be similar
//gs -dNOPAUSE -sDEVICE=pdfwrite -sOUTPUTFILE=C:/Apache24/htdocs/samplepdfs/NewMergedPDF.pdf -dBATCH C:/Apache24/htdocs/samplepdfs/one.pdf C:/Apache24/htdocs/samplepdfs/two.pdf C:/Apache24/htdocs/samplepdfs/three.pdf
exec($cmd);
?>
上面的代码将三个 PDF 文件作为输入,并将它们合并为一个 PDF。
posted @ 2024-06-25 18:21  php冉  阅读(224)  评论(0)    收藏  举报