Search code examples
phphtmldompdf

make dompdf skip first page when numbering pages with {PAGE_NUM}


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));

Solution

  • 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));
      }
    ');