Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

RodrigoG's avatar

total number of pages in a php variable domPDF

Hello, I would like to store in a variable the total number of pages of the domPDF document to, for example, use it in a condition outside the script. How did you solve it in the end, thanks! I have looked for information and what I get is the numbering of the pages in addition to that I get it in a script tag inside the view. This is not worth me:

    <script type="text/php">
        if (isset($pdf)) {
            $x = 250;
            $y = 10;
            $text = "{PAGE_COUNT}";
            $font = null;
            $size = 14;
            $color = array(255,0,0);
            $word_space = 0.0;  //  default
            $char_space = 0.0;  //  default
            $angle = 0.0;   //  default
            $pdf->page_text($x, $y, $text, $font, $size, $color, $word_space, $char_space, $angle);
        }
    </script>

I want to be able to handle the total number of pages in any part of the view like this:

Example-> $pages; ($pages = 2)

0 likes
2 replies
automica's avatar

@rodrigog

use it in a condition outside the script.

where does this script tag live? inside the Dom pdf object?

if you want to count the pages in a pdf, once you have made it, the following code snippet will do:

$path = 'path/to/your/document.pdf';

$totoalPages = countPages($path);

echo $totoalPages;

function countPages($path) {

  $pdftext = file_get_contents($path);

  $num = preg_match_all("//PageW/", $pdftext, $dummy);

  return $num;

}
RodrigoG's avatar

@automica My controller:

// Generate PDF
public function pdf(Invoice $invoice) 
{
    try {
        $pdf = PDF::loadView('admin.invoices.pdf', compact('invoice'));
        $pdf->setPaper('A4');
        return $pdf->stream("FRA_".$invoice->no.".pdf");

    } catch (\Throwable $th) {

        report($th);
        return back()->with('error');
    }
}

I can't use "path" because I use pdf-> stream, right? I use the tag I was talking about in the view, inside 'body' tag, that's where I design the invoice with Css and the data passed from the controller that I have detailed with the $invoice variable.

Please or to participate in this conversation.