我的代码仅将页脚添加到所有页面,但不添加页眉。 我正在 Laravel 项目中执行此操作。
// ReportController.php
$mpdf = new Mpdf();
$pagecount = $mpdf->SetSourceFile($request->file('document')->getPathname());
for ($i = 1; $i <= $pagecount; $i++) {
$mpdf->AddPage();
$importedPage = $mpdf->ImportPage($i);
$mpdf->UseTemplate($importedPage);
$mpdf->SetHTMLHeader('Your header content here.');
$mpdf->SetHTMLFooter('Your footer content');
}
$newPdfPath = storage_path('app/public/new_pdf_with_header_footer.pdf');
$mpdf->Output($newPdfPath, \Mpdf\Output\Destination::FILE);
我什至尝试在 for 循环之前查看页眉和页脚。
$mpdf->SetHTMLHeader('Your header content here.');
$mpdf->SetHTMLFooter('Your footer content');
for ($i = 1; $i <= $pagecount; $i++) {
$mpdf->AddPage();
// ...
}
仍然只添加页脚。
您面临的问题是由于操作顺序造成的。
SetHTMLHeader
和 SetHTMLFooter
方法应在 AddPage
方法之后调用。这是因为当您调用 AddPage
时,它会创建一个没有页眉或页脚的新页面。所以,添加页面后需要设置页眉和页脚。
$mpdf = new Mpdf();
$pagecount = $mpdf->SetSourceFile($request->file('document')->getPathname());
for ($i = 1; $i <= $pagecount; $i++) {
$mpdf->AddPage();
$importedPage = $mpdf->ImportPage($i);
$mpdf->UseTemplate($importedPage);
$mpdf->SetHTMLHeader('Your header content here.');
$mpdf->SetHTMLFooter('Your footer content');
}
$newPdfPath = storage_path('app/public/new_pdf_with_header_footer.pdf');
$mpdf->Output($newPdfPath, \Mpdf\Output\Destination::FILE);
这应该将页眉和页脚添加到 PDF 中的所有页面。