Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dompdf Numbering pages but skip first one

Tags:

I use dompdf class and I need page numembering for every page

I did this and it works:

$dompdf = new Dompdf();
$dompdf->load_html($html);
$dompdf->render();

$canvas = $dompdf->get_canvas();
$font = $dompdf->getFontMetrics()->get_font("helvetica", "bold");

$canvas->page_text(72, 18, "Header: {PAGE_NUM}", $font, 6, array(0,0,0));

What I need is just skip first page and start numbering from second page.

How can I do this?

like image 765
Oto Shavadze Avatar asked Nov 22 '18 13:11

Oto Shavadze


1 Answers

Here is what worked for me:

$dompdf = new Dompdf();
$dompdf->load_html($html);
$dompdf->render();

$canvas = $dompdf->get_canvas();
$cpdf = $canvas->get_cpdf();

$font = $dompdf->getFontMetrics()->get_font("helvetica", "bold");

$firstPageId = $cpdf->getFirstPageId();
$objects = $cpdf->objects;
$pages = array_filter($objects, function($v) {
    return $v['t'] == 'page';
});
$number = 1;
foreach($pages as $pageId => $page) {
    if(($pageId + 1) !== $firstPageId) {
        $canvas->reopen_object($pageId + 1);
        $canvas->text(72, 18, "Header: $number", $font, 6, array(0,0,0));
        $canvas->close_object();
        $number++;
    }
}

$dompdf->stream();

How this works:

  1. Get all the pages from https://github.com/dompdf/dompdf/blob/v0.8.2/lib/Cpdf.php#L32
  2. Add the text to all except the 1st page.
like image 169
Jannes Botis Avatar answered Oct 14 '22 00:10

Jannes Botis