我首先要说的是,我可以使用 mPDF 生成 PDF,但就我的生活而言,我无法将现有 PDF 与它刚刚生成的 PDF 合并。
我需要弄清楚的是如何将现有 PDF 附加/添加到新生成的 PDF 中。我试过使用 mPDF 方法导入页面,但我只能得到如下错误:
mPDF error: Cannot open '/downloads/test.pdf'.
上面的消息是模棱两可的,不清楚为什么它不能打开文件... 这是我用来尝试合并 PDF 的代码:
include_once("./pdf/mpdf/mpdf.php");
$output_file = $_GET['output_file'];
$url = $_GET['input_file'];
$technical_drawing = $_GET['tech_drawing'];
$html = file_get_contents($url);
$mpdf = new mPDF('utf-8','Letter','','',0,0,0,0,0,0,'P');
$mpdf->SetImportUse();
$pagecount = $mpdf->SetSourceFile($technical_drawing);
$tplIdx = $mpdf->ImportPage($pagecount);
$mpdf->UseTemplate($tplIdx);
$mpdf->WriteHTML($html);
$mpdf->Output($output_file, 'D');
exit;
$output_file 将是显示给用户的文件名。 $url 是我们在生成 PDF 期间写入文件的 HTML。 $technical_drawing 是我们要附加/合并生成的 PDF 的 PDF 的相对路径。
我知道我可以使用类似 ghostscript 的东西,但我在客户端的服务器上没有那种类型的访问权限。
让我知道是否有人使用 mPDF 找到了此问题的解决方案,或者如果我是 S.O.L.并且需要找到另一个库来进行 PDF 合并。我真的在寻找解决方案或建议,而不仅仅是指向另一个库的链接。我已经用尽了在 Google 或 mPDF 文档中可以找到的描述我遇到的错误的内容。
编辑:从 http://example.com/pdf/example.pdf 更改了 mPDF 错误到“/downloads/test.pdf”。
EDIT_2:代码已修复为采用相对路径。
这是最终的工作代码。如果有人知道如何指定将 HTML 写入 PDF 文档的顺序,将页面导入为最后一页(自定义页面大小与 HTML 的页面大小不同),则奖励。
include_once("./pdf/mpdf/mpdf.php");
$output_file = 'test-' . $_GET['output_file'];
$url = $_GET['input_file'];
$technical_drawing = $_GET['tech_drawing'];
$html = file_get_contents($url);
if(!file_exists($technical_drawing)) {
$mpdf = new mPDF('utf-8','Letter','','',0,0,0,0,0,0,'L');
} else {
$mpdf = new mPDF('utf-8','A3-L','','',0,0,0,0,0,0,'L');
$mpdf->SetImportUse();
$pagecount = $mpdf->SetSourceFile($technical_drawing);
$import_page = $mpdf->ImportPage();
$mpdf->UseTemplate($import_page);
// Add Last page
$mpdf->AddPageByArray(array(
'orientation' => 'P',
'ohvalue' => 1,
'ehvalue' => -1,
'ofvalue' => -1,
'efvalue' => -1,
'newformat' => 'Letter'
));
}
$mpdf->WriteHTML($html);
$mpdf->Output($output_file, 'D');
exit;
最佳答案
我像这样合并 pdf - {所有文件中的所有页面}:
$this = 扩展 mPDF 类的类...
function mergePDFFiles(Array $filenames, $outFile)
{
if ($filenames) {
$filesTotal = sizeof($filenames);
$fileNumber = 1;
$this->SetImportUse(); // this line comment out if method doesnt exist
if (!file_exists($outFile)) {
$handle = fopen($outFile, 'w');
fclose($handle);
}
foreach ($filenames as $fileName) {
if (file_exists($fileName)) {
$pagesInFile = $this->SetSourceFile($fileName);
for ($i = 1; $i <= $pagesInFile; $i++) {
$tplId = $this->ImportPage($i); // in mPdf v8 should be 'importPage($i)'
$this->UseTemplate($tplId);
if (($fileNumber < $filesTotal) || ($i != $pagesInFile)) {
$this->WriteHTML('<pagebreak />');
}
}
}
$fileNumber++;
}
$this->Output($outFile);
}
}
关于PHP - 如何使用 mPDF 合并 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26414298/