How to get page number on dompdf PDF when using "view"
Asked Answered
S

9

21

Ok, so I use the following snippet to get "views" of HTML with PHP variables loaded in as $data so that I can do things like fill in tr's of data from a database call or whatever.

function getView ($file, $data=NULL) {
    if (!empty($data)) extract($data);
    ob_start();
    if (is_file($file)) include($file);
    return ob_get_clean();
}

Gets used for something like, $htmlPDF = getView('receipt.php', array( 'orderNumber' => $orderNumber )); Where $orderNumber is then used in the HTML to fill in it's proper places. For instance something like:

<h1>You Order #<?= $orderNumber; ?></h1>


Ok, so point is, that's how I get my HTML. I then load it to my dompdf variable as:
$dompdf = new DOMPDF();
$dompdf->load_html($html);
$dompdf->render();

Which all works great. The problem is getting the inline php script to work to get PAge Numbers / Page Headers|Footers. I've followed the directions here best I can, but I can't seem to make the right blend. Thus far, not having any errors, except I get 0 Page Numbers anywhere!

And yes I've looked at pages like Header in PDF page using DOMPDF in PHP and dompdf page number, but still no forward progress, at all! I'm wondering if the inline php scripting has to do with how I'm getting the HTML as a string? Any pointers, ideas, advice?

Stylopodium answered 14/11, 2013 at 16:53 Comment(0)
S
20

Update Regarding changes with version of dompdf >= 0.7.0
1. Because the dompdf_config.inc.php file has been removed from this release (and is no longer referenced) all dompdf options should be set at run time.
4. The FontMetrics class is now instantiated instead of static. To simplify migration of embedded scripts from earlier versions of dompdf we provide access to the instantiated FontMetrics class via the $fontMetrics variable. Please update your embedded scripts. For example, FontMetrics::get_font('helvetica') would now be $fontMetrics->getFont('helvetica').
~ Thanks to Dennis Ameling's answer for the updated information.

Found my answer by looking over the dompdf_config.inc.php file. As it turns out, DOMPDF_ENABLE_PHP is set to false thus causing the inline php script to be ignored. I simply edited dompdf_config.custom.inc.php to the following and all is fine and working with the later code in the view.

In dompdf/dompdf_config.custom.inc.php

<?php
    define("DOMPDF_ENABLE_PHP", true);

At Run Time

$dompdf->set_option("isPhpEnabled", true);

Then, in my html file

<body>
    <script type="text/php">
        if ( isset($pdf) ) {
            // OLD 
            // $font = Font_Metrics::get_font("helvetica", "bold");
            // $pdf->page_text(72, 18, "{PAGE_NUM} of {PAGE_COUNT}", $font, 6, array(255,0,0));
            // v.0.7.0 and greater
            $x = 72;
            $y = 18;
            $text = "{PAGE_NUM} of {PAGE_COUNT}";
            $font = $fontMetrics->get_font("helvetica", "bold");
            $size = 6;
            $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>
    <div

If you go this route, don't forget to restart Apache

Stylopodium answered 14/11, 2013 at 19:15 Comment(4)
It's very important to use <script> tags and not regular <?php ?> tags. Regular tags are ignored.Poston
This works. But if you see that the page is ever loading, you will need to choose a different font (see dompdf/dompdf/lib/fonts)Staff
This is only adding page number to first page. I'm loading data via foreach loop and each loop iteration can have different height. How can I handle that?Bonni
if you need on page bottom $y = 825; // Adjust the vertical position as needed $x = 530; // Adjust the horizontal position as neededLaurentia
A
17

I have a simple code to showing page number in footer of every page of dom pdf

#footer { position: fixed; right: 0px; bottom: 10px; text-align: center;border-top: 1px solid black;}
        #footer .page:after { content: counter(page, decimal); }
 @page { margin: 20px 30px 40px 50px; }

above code is css code

<div id="footer">
    <p class="page">Page </p>
  </div> 

You can change text position according to your requirement

Alsace answered 6/7, 2019 at 12:19 Comment(1)
Hi kishan may be it will be hidden bcz of margin change your margin according to your page contentAlsace
B
16

If you're using DOMPDF >= 0.7.0, the dompdf_config.inc.php file has been removed and adding a page number now requires a slightly different approach:

Because the dompdf_config.inc.php file has been removed from this release (and is no longer referenced) all dompdf options should be set at run time.

To enable PHP code to be executed by DOMPDF, use:

$dompdf->set_option("isPhpEnabled", true);

Also, FontMetrics should now be called by using $fontMetrics instead of Font_Metrics, so the code mentioned by @user1231342435346354 changes slightly:

<script type="text/php">
if ( isset($pdf) ) { 
    $pdf->page_script('
        if ($PAGE_COUNT > 1) {
            $font = $fontMetrics->get_font("Arial, Helvetica, sans-serif", "normal");
            $size = 12;
            $pageText = "Page " . $PAGE_NUM . " of " . $PAGE_COUNT;
            $y = 15;
            $x = 520;
            $pdf->text($x, $y, $pageText, $font, $size);
        } 
    ');
}
</script>
Bane answered 5/8, 2016 at 11:56 Comment(5)
This is now the preferred way to set options: $options = new Options(); $options->set('isPhpEnabled', TRUE); $dompdf = new Dompdf($options);Foreknow
This is the only solution that worked for me after getting through about 7-8 pages of stackoverflow. If you are using the version 0.7+ this is the way to go.Rase
This code adds page number correctly but it also adds an empty page as a first page. Do you have any idea how I can remove that empty page?Banderilla
Any idea why I get this error? Object of class Barryvdh\DomPDF\PDF could not be converted to string? On the line inside the script checking if $pdf is set. ThanksHerzig
If you need it on page bottom $y = 825; // Adjust the vertical position as needed $x = 530; // Adjust the horizontal position as neededLaurentia
H
5

Code that worked for me. You can customize where is should be located depending on the size of your PDF:

$pdf->loadView('your_view', $data);
$pdf->output();
$dom_pdf = $pdf->getDomPDF();

$canvas = $dom_pdf->get_canvas();
$canvas->page_text(0, 0, "{PAGE_NUM} of {PAGE_COUNT}", null, 10, array(0, 0, 0));

Remember that color array doesn't contain RGB values. Appropriate values you can take from row RYB here as a value in range (0,1), i.e. array(0.46,0.46,0.46).

Hydrosphere answered 11/7, 2021 at 19:58 Comment(0)
V
4

Improved version of Dennis Ameling's answer to take into account…

Translation and text centering

Do not forget to enable PHP support like this $dompdf->set_option("isPhpEnabled", true); (or, if you're using laravel-dompdf PDF::setOptions(['isPhpEnabled' => true]);).

<script type="text/php">
    if (isset($pdf)) {
        $pdf->page_script('
            $text = sprintf(_("Page %d/%d"),  $PAGE_NUM, $PAGE_COUNT);
            // Uncomment the following line if you use a Laravel-based i18n
            //$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);
        '); // End of page_script
    }
</script>

But

If you only need $pageNum, using a CSS counter is a way simpler approach!

Variance answered 26/5, 2020 at 15:15 Comment(0)
W
2

Code that work for me!

  1. For Laravel, if you are using barryvdh / laravel-dompdf (Which I used),

change "enable_php" => true, in following file

 vendor/barryvdh/laravel-dompdf/config/dompdf.php
  1. Add following script code in your blade where you add HTML code for PDF.
    <script type="text/php"> 
    
    if (isset($pdf)) { 
     //Shows number center-bottom of A4 page with $x,$y values
        $x = 250;  //X-axis i.e. vertical position 
        $y = 820; //Y-axis horizontal position
        $text = "Page {PAGE_NUM} of {PAGE_COUNT}";  //format of display message
        $font =  $fontMetrics->get_font("helvetica", "bold");
        $size = 10;
        $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> 

Hope it will work for someone!

Wayside answered 10/6, 2022 at 9:52 Comment(0)
D
0

Easy Method: Using CSS and dompdf Add Page numbers like 1 of 5. you can add pdf page numbers using CSS and specify the Header or Footer tag in the content. Add Footer or Header tag in content

CSS to add page numbers dompdf functions dompdf placeholder

 function injectPageCount(Dompdf $dompdf): void{
            /** @var CPDF $canvas */
            $canvas = $dompdf->getCanvas();
            $pdf = $canvas->get_cpdf();
            foreach ($pdf->objects as &$o) {
                if ($o['t'] === 'contents') {
                    $o['c'] = str_replace('DOMPDF_PAGE_COUNT_PLACEHOLDER', $canvas->get_page_count(), $o['c']);
                }
            }
        }
Duro answered 22/4, 2022 at 6:42 Comment(3)
Please post your code as text, not as an image. Look here why it's not a good idea to use images or screenshots.Finedrawn
Ok, I'll upload code instead of an image. ThanksDuro
$canvas->get_page_count() is ok.... but $canvas->get_page_number() return always same number for each pageReading
B
0

Even though this is very old, and hopefully the author managed to make this work by then, none of these solutions worked for me with dompdf version 2. So here is what worked, if that can be of any help of whoever falls on this page after some Googling:

<?php
use Dompdf\Dompdf;
use Dompdf\Options;

$options = new Options;
$options->set('isPhpEnabled', 'true'); // allow php code in html

$dompdf = new Dompdf($options);
$dompdf->setPaper("A4", "portrait");
$html = file_get_contents("dompdf-template.php"); // import html template

$contract_nb = '3974G3U33E';
$name = 'john';
$table_lines = ''; // if the table is too long to fit in one page, some blank space will be added before the table starts, so instead, we create one table per line.
for ($i = 0; $i < 120; $i++) // loop many times the same line just to create some content
{
    $table_lines .= '<table>';
        $table_lines .= '<tbody>';
            $table_lines .= '<tr>';
                $table_lines .= '<td>A sample product</td>';
                $table_lines .= '<td style="text-align: right;">' . $i . '</td>';
            $table_lines .= '</tr>';
        $table_lines .= '</tbody>';
    $table_lines .= '</table>';
}
// replace some values in the html template
$html = str_replace(['{contract_nb}', '{name}', '{table_lines}'], [$contract_nb, $name, $table_lines], $html);
$dompdf->loadHtml($html);

$dompdf->render(); // we render the pdf so the number of pages can be calculated

// add pagination
$canvas = $dompdf->getCanvas(); // get the canvas
// add the page number and total number of pages
$canvas->page_script('
    $text = "$PAGE_NUM / $PAGE_COUNT";
    $pdf->text(535, 791.89, $text, \'Helvetica\', 10, array(0,0,0));
');

$dompdf->stream('generated-file-' . time() . '.pdf', ['Attachment' => 0]);
?>

Hope that helps!

Brooch answered 28/3, 2023 at 5:39 Comment(0)
F
0

A little later but I'm using this to display the number page on each page:

<style>
footer:after {
   content:"Page " counter(page);
}
</style>

However I am unable to display the total number of pages...

Firn answered 11/8, 2023 at 14:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.