Skip to main content
Tutorial Free

Laravel DomPDF: How to Add Page Numbers

June 04, 2025
2 min read

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.

Enjoyed This Tutorial?

Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.

Comments & Discussion

No comments yet…

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.