Header in PDF page using DOMPDF in PHP
Asked Answered
D

5

45

I am creating a PDF file using DOMPDF. I have a big content to extract in PDF, we need some header in all the pages. So can anyone telme how to add a header and footer in the PDF so that the header will shown in all the pages using DOMPDF.

Dulce answered 20/9, 2011 at 11:23 Comment(0)
A
72

In the 0.6.0 code you will be able to use HTML+CSS to generate headers and footers. There are a few limitations when compared to using inline PHP (e.g. no PAGE_COUNT placeholder yet), so whether or not this is viable depends on your needs.

The following code will produce a two-page document with a header and footer:

<html>
<head>
  <style>
    @page { margin: 180px 50px; }
    #header { position: fixed; left: 0px; top: -180px; right: 0px; height: 150px; background-color: orange; text-align: center; }
    #footer { position: fixed; left: 0px; bottom: -180px; right: 0px; height: 150px; background-color: lightblue; }
    #footer .page:after { content: counter(page, upper-roman); }
  </style>
<body>
  <div id="header">
    <h1>Widgets Express</h1>
  </div>
  <div id="footer">
    <p class="page">Page </p>
  </div>
  <div id="content">
    <p>the first page</p>
    <p style="page-break-before: always;">the second page</p>
  </div>
</body>
</html>

You could also use a combination of the two styles if you needed access to some of the missing functionality. PDF objects and text added using the page_text method render on top of the HTML content.

Astra answered 20/9, 2011 at 17:56 Comment(5)
Hi, Brian.. Plus 1 for your wonderful tutorial. you made it very easy :)Javierjavler
@Astra does dompdf respect the pages counter? I haven't been able to get it to work. This is what I'm talking about content: counter(page) " of " counter(pages);Barabbas
@Barabbas dompdf is currently unable to display the total number of pages in this way. The only method of accessing this information is via inline script.Astra
saved my life with this one... Just need a logo on each page.Intrench
Important to know: Placing the header and footer at the beginning of the code will print them on every page. Placing them at the end will omit the header and footer on the first page. Also the header and footer tags need to be direct childs of the body. Source: agoradesign.at/blog/…Parfait
S
24

There is a FAQ entry on the DOMPDF wiki: Is there a way to add headers and footers or page numbers?.

So you can either add the following "inline PHP"-snippet to your HTML-input (add a similar page_text-call for your footer):

<script type="text/php">
    if ( isset($pdf) ) {
        $font = Font_Metrics::get_font("helvetica", "bold");
        $pdf->page_text(72, 18, "Header: {PAGE_NUM} of {PAGE_COUNT}",
                        $font, 6, array(0,0,0));
    }
</script>    

If you rather want to implement this on your caller-side (meaning in the PHP code directly) you have to call the DOMPDFS's get_canvas()-method which returns the underlying PDF-Renderer which allows you to call the page_text method like in the example above. Let me show you what I mean:

// your dompdf setup        
$dompdf = new DOMPDF();

$dompdf->load_html($html);
$dompdf->render();

// add the header
$canvas = $dompdf->get_canvas();
$font = Font_Metrics::get_font("helvetica", "bold");

// the same call as in my previous example
$canvas->page_text(72, 18, "Header: {PAGE_NUM} of {PAGE_COUNT}",
                   $font, 6, array(0,0,0));

Eventually you have to call page_text after load_html (just try it out).

Sara answered 20/9, 2011 at 12:28 Comment(6)
Thanks vstm... I am trying to print some html tags in the header. I tried TCPDF too.. but in that I can't able to use HTML tags its only support text. In my requirement I have to create a report and the report header or the column names should be shown in all the pages. I can't find any thing that print my HTML header in the PDF. If you know something please help me.Dulce
your second part of the code is the better one, no inline script php code. but the "// add the header" part must be after "$dompdf->render();" in order to work.Cannibalism
You should enable 'DOMPDF_ENABLE_PHP' for the first part of this answer to work which is a real security risk. You cannot use this for external websites or user generated html. When using user generated content you should be 100% sure everything is escaped properly before enabling this option.Gynarchy
Debugging I've found $canvas = nullMadelina
I updated the code snippet so the method calls are in the correct order and the example works now.Beneficiary
In 0.7.0 Font_Metrics is now available in the dompdf object $font = $dompdf->getFontMetrics()->get_font("helvetica", "bold");Correna
I
11

If you want to get something similar to: enter image description here

Define as follows, header, footer and content of your document:

<html>
    <head>
        <style>
            @page {
                margin: 100px 25px;
            }

            header {
                position: fixed;
                top: -60px;
                height: 50px;
                background-color: #752727;
                color: white;
                text-align: center;
                line-height: 35px;
            }

            footer {
                position: fixed;
                bottom: -60px;
                height: 50px;
                background-color: #752727;
                color: white;
                text-align: center;
                line-height: 35px;
            }
        </style>
    </head>
    <body>
        <header>
            Header
        </header>

        <footer>
            Footer
        </footer>

        <main>
            <!-- Your main content -->
        </main>
    </body>
</html>
Ibbetson answered 25/6, 2021 at 13:59 Comment(3)
Don't think this will add a header and footer to every page, will it? If the content spans two pages, I think the second page will come out without a header and footer. 🤔Sheelah
It will add to every page.Ibbetson
Thank you! Was hard to believe, but today I tried it and found it working. :-) For anyone wondering about the version, I'm on 1.0.2.Sheelah
G
3

You need This code, I hope help you

Regards...

# Instanciamos un objeto de la clase DOMPDF.
$dompdf = new DOMPDF();

# Definimos el tamaño y orientación del papel que queremos.
# O por defecto cogerá el que está en el fichero de configuración.
$dompdf->set_paper("Letter", "portrait");

# Cargamos el contenido HTML.
$dompdf->load_html(utf8_decode($html));

# Renderizamos el documento PDF.
$dompdf->render();

#Esto es lo que imprime en el PDF el numero de paginas
$canvas = $dompdf->get_canvas();
$footer = $canvas->open_object();
$w = $canvas->get_width();
$h = $canvas->get_height();
$canvas->page_text($w-60,$h-28,"Página {PAGE_NUM} de {PAGE_COUNT}", Font_Metrics::get_font('helvetica'),6);
$canvas->page_text($w-590,$h-28,"El pie de p&aacute;gina del lado izquiero, Guadalajara, Jalisco C.P. XXXXX Tel. XX (XX) XXXX XXXX", Font_Metrics::get_font('helvetica'),6);

$canvas->close_object();
$canvas->add_object($footer,"all");

# Enviamos el fichero PDF al navegador.
//$dompdf->stream('FicheroEjemplo.pdf');

# Para grabar en fichero en ruta especifica
$output = $dompdf->output();
file_put_contents('ejemplo.pdf',$output);

 #Liberamos 
unset($dompdf);
Graiggrail answered 11/7, 2018 at 13:11 Comment(0)
D
-1

use blade only with something like this

<!doctype html>
<html lang="en">
<head>
        <style>
header { position: absolute; top: -70px; left: 0px; right: 0px; height: 150px; margin-bottom: 10em }
        </style>
</head>
<body>
       <header>
            <table border="0" width="100%" style="font-size:1em" class="tb-header">
                <tr>
                    <td width="83%" class="left-align" >
                        <tr>
                            <td>
                                <span class="invoice-number mr-1" style="font-size:1em">Purchase Invoice # {{ $data->code }}</span>
                            </td>
                        </tr>
                        <tr>
                            <td style="margin-top: -2px;">
                                <small style="font-size:1em">Diajukan: {{ date('d/m/y',strtotime($data->post_date)) }}</small>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <h5 style="margin-top: -2px">Purchase Invoice</h5>
                            </td>
                        </tr>
                                
                        
                    </td>
                    <td width="33%" class="right-align">
                        
                        
                   
                    </td>
                    
                    <td width="34%" class="right-align">
                        
                            <img src="{{ $image }}" width="50%" style="position: absolute; top:5px; width:20%">
                       
                    </td>
                </tr>
                
            </table>
            <hr style="border-top: 3px solid black; margin-top:-2%">
        </header>
<main>
</main>
</body>

after this header will be rendered in each pdf
Remember!tag header must be on the body before the tag main

Dean answered 26/5, 2023 at 6:42 Comment(1)
What is the change in your answer, the answer already given in above.Stratocracy

© 2022 - 2025 — McMap. All rights reserved.