Longtable breaks afterpage

My problem is that I want to have a certain footer on the first, or the last, page. The solution I've tried with is by using fancyhdr together with afterpage.

Here is a working example, without longtable, of what I want.

\documentclass[12pt,a4paper]{article}
\usepackage{fancyhdr}
\usepackage{longtable}
\usepackage{afterpage}
\pagestyle{fancy}
\begin{document}
\lfoot{
Footer page 1
}%end lhead eller lfoot
\afterpage{\clearpage
\lfoot{
Footer page 2 and forward
}%end lfoot
}%end afterpage

Test page 1
\newpage
Test page 2
\newpage
Test page 3
\end{document}


As you can see, the left footer are different on page 1 vs page 2 and 3.

But when I use a longtable which spans over these pages, the afterpage-technique don't work. Unless I force a newpage, which I really don't want to do. As you can see in the following example:

\documentclass[12pt,a4paper]{article}
\usepackage{fancyhdr}
\usepackage{longtable}
\usepackage{afterpage}
\pagestyle{fancy}
\begin{document}
\lfoot{
Footer page 1
}%end lhead eller lfoot
\afterpage{\clearpage
\lfoot{
Footer page 2 and forward
}%end lfoot
}%end afterpage
\begin{longtable}{|l| l|}
Lots of lines& like this.\\
...
Lots of lines& like this.\\
\end{longtable}
After longtable
\newpage
After newpage
\end{document}

• Your usage of \afterpage is for having a different footer on page 1 than on the subsequent pages? – egreg Sep 26 '14 at 14:20
• Yes. I see now that I initially wrote 'header' in my first sentence. I'm changing that to footer. If that were confusing you. – Joakim Sep 26 '14 at 14:25
• Using \afterpage for that purpose is a sledgehammer for a mosquito. Define a firstpage style with \fancypagestyle and issue \thispagestyle{firstpage} just after \begin{document}. – egreg Sep 26 '14 at 14:26
• I will be more that happy if you can give me a better solution. I'm not sure where I got this solution from a couple of years ago. – Joakim Sep 26 '14 at 14:28

1 Answer

Both \afterpage and longtable act during the phase in which TeX ships out a page, so they are very likely to enter in conflict with each other.

Using \afterpage for the purpose of changing footer after the first page is not recommendable.

\documentclass{article}

\usepackage{fancyhdr}
\pagestyle{fancy}
\fancyhf{}
\fancyfoot[L]{footer for all pages}

\fancypagestyle{firstpage}{%
\fancyhf{}%
\fancyfoot[L]{footer for page 1}%
}

\begin{document}
\thispagestyle{firstpage}

<any contents>

\end{document}

• That looks really good. Must fancypagestyle's be declared before begin document? – Joakim Sep 27 '14 at 6:59
• @Joakim Not necessarily, but it's better to have it there, so definitions and set up declarations are in a single place. – egreg Sep 27 '14 at 9:46