Css Hack: Print Repeating Headers and Footers in Chrome

When you want your web application to be able to export a PDF, you have basically 2 ways to go: either you use some server-side pdf generator, either you code your pdf as a web page within your app, and lets your users print it with their browser.

Personally I like the 2nd option, since it allows me to design the pdf like a web page, and use my web and design frameworks (React and Material UI). Problem is, when you use Chrome print function, it automatically generates headers and footers on each printed page, and you can’t customize those.

After searching for a long time over Stackoverflow and other similar sites, it seems there was no easy way to customize Chrome-generated headers and footers. Some people recommended unsupported CSS, others recommended using tables, but nothing really worked. I finally came across this Stackoverflow post which gave me the magic trick: elements with CSS position:fixed; are automatically repeated by Chrome on each printed page.

So, if you want your web page to have headers and footers on each printed page,

1- Remove the automatically generated Chrome headers and footers with this css:

@page{ size:auto; margin:5mm;}

2- Add for example your footer in a div on your page with class “footer” and use this css (tweak bottom and left values depending on your footer content):

@media screen {
  .footer {
    display: none
  }
}
@media print {
  .footer {
    position: fixed;
    bottom: 5px;
    left: 10px;
  }
}

Now when you print your web page with Chrome, you will see on each page your own footer.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s