我下面的代码完美地将页码添加到文档右下角的每个页面中。
我有一个不需要页码的标题页,因此想跳过该页码。
有没有办法做到这一点?还是至少将代码修改为page_num + 1,page_count-1,然后将div覆盖在标题页上,以使其不显示?
$dompdf->render();
$canvas = $dompdf->get_canvas();
$font = Font_Metrics::get_font("helvetica", "bold");
$canvas->page_text(522, 770, "Page: {PAGE_NUM} of {PAGE_COUNT}", $font, 10, array(0,0,0));
您无法使用page_text()
方法执行此操作,因为此方法将指定的文本应用于所有页面。您想使用的是page_script()
方法,该方法具有类似于dompdf的嵌入式脚本的功能,可在所有页面上运行。
由于只需要减去第一页,所以您可以从当前页面和页面总数中减去一个以获得正确的页面编号。
尝试在dompdf 0.6.2或更早版本中进行以下操作:
$dompdf->render();
$canvas = $dompdf->get_canvas();
$canvas->page_script('
if ($PAGE_NUM > 1) {
$font = Font_Metrics::get_font("helvetica", "bold");
$current_page = $PAGE_NUM-1;
$total_pages = $PAGE_COUNT-1;
$pdf->text(522, 770, "Page: $current_page of $total_pages", $font, 10, array(0,0,0));
}
');
从dompdf 0.7.0开始有点不同:
$dompdf->render();
$canvas = $dompdf->getCanvas();
$canvas->page_script('
if ($PAGE_NUM > 1) {
$font = $fontMetrics->getFont("helvetica", "bold");
$current_page = $PAGE_NUM-1;
$total_pages = $PAGE_COUNT-1;
$pdf->text(522, 770, "Page: $current_page of $total_pages", $font, 10, array(0,0,0));
}
');
接受的答案对我不起作用。为什么不只检查页码而忽略第一页呢?像这样的东西
$pdf->page_script ('
if ($PAGE_NUM != 1) {
$current_page = $PAGE_NUM;
$pdf->text(550, 750, "Page $current_page", null, 10, array(0,0,0));
}
');
这与accepted answer相同,但是借助于带有静态函数的类,因此我们不必在字符串内进行编码。
班级
<?php
namespace App\Services;
use Dompdf\Canvas;
use Dompdf\FontMetrics;
class PdfService
{
public static function outputPageNumbers(Canvas $pdf, FontMetrics $fontMetrics, $PAGE_NUM, $PAGE_COUNT) {
if ($PAGE_NUM > 1) {
$font = $fontMetrics->getFont("helvetica", "bold");
$current_page = $PAGE_NUM-1;
$total_pages = $PAGE_COUNT-1;
$pdf->text(522, 770, "Page: $current_page of $total_pages", $font, 10, array(0,0,0));
}
}
}
并使用page_script
调用静态函数
$dompdf->render();
$canvas = $dompdf->getCanvas();
$canvas->page_script(
'\App\Services\ProductPdfsService::outputPageNumbers($pdf, $fontMetrics, $PAGE_NUM, $PAGE_COUNT);'
);