I have the following code below that perfectly adds the page number to each of my pages in the bottom right corner of the document.
I have a header page that DOES NOT need a page number, so would like to skip the number for it.
Is there a way of doing this? or at the very least modifying the code to be page_num+1, page_count-1, and then div over the header page so that it doesnt show?
$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));
You can't do this using the page_text()
method since this method applies the specified text on all pages. What you would want to use instead is the page_script()
method which gives you capabilities similar to dompdf's embedded script, run on all pages.
Since you only need to subtract out the first page you can just subtract one from the current page and page total to get the correct page numbering.
Try the following in dompdf 0.6.2 or earlier:
$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));
}
');
Things are a bit different starting with 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));
}
');
The accepted answer did not work for me. Why not just check the page number and ignore if first page? Something like this
$pdf->page_script ('
if ($PAGE_NUM != 1) {
$current_page = $PAGE_NUM;
$pdf->text(550, 750, "Page $current_page", null, 10, array(0,0,0));
}
');
This is the same as the accepted answer but with the help of a class with a static function so that we don't have to code inside a string.
The Class
<?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));
}
}
}
and calling the static function with page_script
$dompdf->render();
$canvas = $dompdf->getCanvas();
$canvas->page_script(
'\App\Services\ProductPdfsService::outputPageNumbers($pdf, $fontMetrics, $PAGE_NUM, $PAGE_COUNT);'
);