Printing HTML headers and footers

A common question I see is how to print headers and footers when printing a webpage. An old stackoverflow post posed this question:

Is it possible to print HTML pages with custom headers and footers on each printed page? I'd like to add the word "UNCLASSIFIED" in red, Arial, size 16pt to the top and bottom of every printed page, regardless of the content.

The person wanted to do this in pure HTML and CSS.

Margin boxes

HTML5 and CSS3 have a very good way to accomplish this with margin boxes. Although this is part of the CSS3 standard, common enduser browsers have not implemented margin boxes as of early 2015. So this approach can work only when using server-side rendering into a PDF as we describe in our two tutorials: Using PDF generation to make beautiful webpage prints and Generating PDFs from HTML.

If server-side PDF generation is an option, then read our explanation of implementing headers and footers.

If server-side PDF generation is not an option, then one approach is to create an HTML element to represent the footer and set it to be  

position: fixed;

 and 

bottom: 0;

The HTML would look like this:

<div class="footer">UNCLASSIFIED</div>

 And the CSS would look like this:

@media screen {
        div.footer {
            display: none;
        }
    }
    @media print {
        div.footer {
            position: fixed;
            bottom: 0;
        }
    }

This does not address page numbering, but it can let you get basic text such as the document title, author, date, and classification level into the header and footer region.

WilliamH

Print Developer Community

I work for HP, but my views and opinions are my own.

 

More from Will

Code Tutorials

Here are Will's detailed code tutorials that we have migrated to Print Fundamentals for Developers on the HP Developers' Portal

Will's blog and forum posts