Add footer text in each page of PDF using CSS

11.9k views Asked by At

I need to apply Header & footer text in each page of PDF, for that i am using below line of CSS.By this I am able to apply Header text in each page but not footer text. I am getting footer text only in last page of PDF.

   @@page {
         @@top {
                content: element(header);
            }

            @@bottom {
                content: element(footer);
            }
        }

        header {
            padding: 10px;
            position: running(header);
            }

     footer {
            padding: 5px;
            position: running(footer);
        } 
3

There are 3 answers

1
Hetal sorthiya On

#footer {
  position: fixed;
  width: 100%;
  bottom: 0;
  left: 0;
  right: 0;
}

#footer p {
  border-top: 2px solid #555555;
  margin-top:10px;
}
<div id="footer">
  <p>footer text</p>
</div>

0
John On

I am assuming you are using something like dompdf to generate your PDFs from HTML. If not, I apologise and found similar code to this elsewhere that produces headers and footers on all pages. This seems to work for printing normally from browser as well as to PDFs.

CSS

<style type="text/css">
<!-- 
@page {
 margin: 2cm;
}

.header, .footer{
 position: absolute;
}

.footer{
 bottom:0;
 height: 40px;
}

.header{
 top: 0;
 height: 40px;
} 

.content{
 margin-top: 45px;
 margin-bottom: 45px;
}
-->
</style>

HTML code

<div class="header">
  Header html goes here
</div>
<div class="content">
  page content goes here
</div>
<div class="footer">
  footer code goes here
</div>

The addition of the content class along with the height specified in the elements header and footer helps stop the content from just writing all over your header and footer on each page.

0
Péé On

I had the same problem, the problem is that you have to put both "footer" and "header" div's at the top of your page, otherwise the footer won't work. No idea why ...