5.6 Add custom headers and footers

The LaTeX package fancyhdr has provided several commands to customize the header and footer lines of your document. For a more complete guide, please refer to the full documentation at https://ctan.org/pkg/fancyhdr. To begin with, we must load the package. Then we can change the header style, e.g.,

\usepackage{fancyhdr}
\pagestyle{fancy}

The package offers three different interfaces, but we will use the commands \fancyhead and \fancyfoot. The syntax for the formatting is \fancyhead[selectors]{output text}, whereby the selectors state the part of the header that we wish to customize. We can use the following selectors for the page locators:

  • E for even pages
  • O for odd pages
  • L for the left side
  • C for the center
  • R for the right side

For example, \fancyhead[LE,RO]{Your Name} will print the text “Your Name” on the left side of the header for even pages, and the right side for odd pages. We can combine this with additional LaTeX commands to extract details from our document for each page:

  • \thepage: the number of the current page.
  • \thechapter: the number of the current chapter.
  • \thesection: the number of the current section.
  • \chaptername: the the word “Chapter” in English, or its equivalent in the current language, or the text that the author specified by redefining this command.
  • \leftmark: the name and number of the current top-level structure in uppercase letters.
  • \rightmark: the name and number of the current next to top-level structure in uppercase letters.

Below is some example LaTeX code that you can add to the preamble using the methods introduced in Section 5.1:

\usepackage{fancyhdr}
\pagestyle{fancy}
% center of header
\fancyhead[CO,CE]{Your Document Header}
% center of footer
\fancyfoot[CO,CE]{And this is a fancy footer}
% page number on the left of even pages and right of odd pages
\fancyfoot[LE,RO]{\thepage}

By default, headers and footers will not be displayed on the first page of your PDF document. If we wish to show our footer on the front page, we must include an additional line \fancypagestyle{plain}{\pagestyle{fancy}}.