Laravel DomPDF: How to Add Page Numbers

When generating a PDF with DomPDF package, you may need a PDF with more than one page. For such cases, you may want to add page numbers at the bottom of page. Here's how.

Notice: This example is based on a longer tutorial on generating a simple invoice PDF using the DomPDF package.


Enable Embedded PHP

First, we must enable embedded PHP. This can be done in two ways: globally in the config or for a specific PDF.

Option 1: Globally

Globally, it can be set in the config/dompdf.php by setting options.enable_php to true.

config/dompdf.php:

return [
// ...
 
'options' => [
 
// ...
 
'enable_php' => false,
 
// ...
 
],
];

If you don't have config published, you do that via an artisan command:

php artisan vendor:publish --provider="Barryvdh\DomPDF\ServiceProvider"

Option 2: Before PDF Render

Setting options before generating a PDF can be done using the setOptions() method, which accepts options as an array.

$pdf = Pdf::loadView('pdf', ['data' => $data]);
$pdf->setOptions(['enable_php' => true]);
 
return $pdf->stream();

Showing Page Numbers

When PHP embed is enabled in the View, the Dompdf\Dompdf instance is accessible through the $pdf variable. In the <script type="text/php">...</script>, we can add code to add page numbers.

// ...
<body>
// ...
 
<script type="text/php">
if (isset($pdf)) {
$pdf->page_script('
$text = __("Page :pageNum/:pageCount", ["pageNum" => $PAGE_NUM, "pageCount" => $PAGE_COUNT]);
$font = null;
$size = 9;
$color = array(0,0,0);
$word_space = 0.0; // default
$char_space = 0.0; // default
$angle = 0.0; // default
 
// Compute text width to center correctly
$textWidth = $fontMetrics->getTextWidth($text, $font, $size);
 
$x = ($pdf->get_width() - $textWidth) / 2;
$y = $pdf->get_height() - 35;
 
$pdf->text($x, $y, $text, $font, $size, $color, $word_space, $char_space, $angle);
');
}
</script>
</body>
</html>

After downloading the PDF, the page number should be in the footer.

No comments or questions yet...

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 78 courses
  • 95 long-form tutorials
  • access to project repositories
  • access to private Discord

Recent New Courses