Tuesday 31 March 2009

Custom Page Numbering with LaTeX

I'm currently doing a home course on short story writing. Or should I say I attempt to as I haven't been returning my assignments very promptly. Anyway, one of the requirements is that each assignment is formatted in such a way that the footer of each page contains the page number, starting at 1 on the first page, and the letters mf for More Follows on every page except the last one. In order to do this, I need to be able to set a specific footer for the last page and one for all other pages. I tried to do that with OpenOffice.org to start with but there was no way to identify whether you were on the last page using a macro with version 2.4, which is what I was using when I started. As you would expect, it is surprisingly easy to do with LaTeX, provided you import the correct packages.

  • In order to specify a custom footer (or header), I will need the fancyhdr package;
  • I will also need to be able to use some if/then/else logic to output something different whether I am on the last page or not, this is provided by the ifthen package;
  • Finally, I will need to know whether I am on the last page, which is provided by the aptly named lastpage package.

Putting all this together, the document's code needs to do the following:

  • Import all relevant packages;
  • Set the page style to fancy;
  • Set all headers and footers to blank;
  • Set the header and footer lines to 0 points (optional, you may like the defaults);
  • Set the right hand side footer so that it implements this logic:
    • If the page is the last one, print nothing;
    • Otherwise, print mf.
  • Set the left hand side footer to the current page's number.

And here is the resulting code:

\documentclass[a4paper,12pt]{article}
\usepackage{lastpage}
\usepackage{ifthen}
\usepackage{fancyhdr}

\pagestyle{fancy}
\fancyhf{}
\renewcommand{\headrulewidth}{0pt}
\renewcommand{\footrulewidth}{0pt}
\fancyfoot[R]{\ifthenelse{\thepage=\pageref{LastPage}}{}{mf}}
\fancyfoot[L]{Page~\thepage}

\begin{document}

The content of the document goes here.

\end{document}

2 comments:

Anonymous said...

This is great! Thank you for posting, using this information I was able to create an AP style document using no header on the first page and the --MORE-- footer on all but the last page which contains a --30-- footer.

%header stuff
\rhead{\fancyplain{}{\ifthenelse{\thepage=1}{}{\thepage\\}}}
\lhead{\fancyplain{}{\ifthenelse{\thepage=1}{}{MyLastName\\ The Slug}}}

% footer stuff
\cfoot{\fancyplain{}{\ifthenelse{\thepage=\pageref{LastPage}}{--30--}{-- MORE --}}}

Unknown said...

I'm glad this worked for you. This shows how powerful Latex can be when you need slightly unusual formatting.