5

I'm trying to add a line in the header to be "Page X of Y", but only if there are multiple pages. My main problem is how to format the if statement. So far I have

    \ifx \pageref{LastPage} 1
    \relax
\else
    \fancyhead[R]{Page \thepage\ of \pageref{LastPage}}
\fi

I think it's the first line that is problematic, as the rest seems to work.

lockstep
  • 250,273
Jamie
  • 373

3 Answers3

7

You can try loading the refcount package and using

\ifnum\getpagerefnumber{LastPage}=1

instead of \ifx\pageref{LastPage}1 (which is wrong for other reasons). See this question.

"Full code":

\usepackage{refcount,lastpage}
\usepackage{fancyhdr}
\fancyhead[R]{%
  \ifnum\getpagerefnumber{LastPage}=1
  \else
    Page \thepage\ of \pageref{LastPage}%
  \fi
}

However, Marco's suggestion to use zref seems to be better:

\usepackage{fancyhdr}
\usepackage[totpages,user]{zref}
\fancyhead[R]{%
  \ifnum\ztotpages=1
  \else
    Page \thepage\ of \ztotpages
  \fi
}
\pagestyle{fancy}
egreg
  • 1,121,712
  • @Gonzalo Ah, yes! I'll add to my answer. – egreg Aug 30 '11 at 19:55
  • For information, I ran into trouble when I tried using etoolbox's \AtEndDocument with the lastpage package loaded. I kept getting Page 3 of 2. The zref-totpages solved my problem and seems more reliable. – jub0bs Nov 21 '13 at 12:55
3

I tried the solution of egreg but it doesn't work. With the hint of Gonzalo Medina(see comment below) it works well (see the example below)

I used the zref packages which is recommended by lastpage

\documentclass{report}
\usepackage{fancyhdr}

\usepackage[totpages,lastpage,user]{zref}
\usepackage{ifthen}
\usepackage{hyperref}
\AtBeginDocument{
\ifthenelse{\ztotpages = 1}{}{\fancyhead[R]{Page \thepage\ of \zpageref{LastPage}}}}
\pagestyle{fancy}
\begin{document}

Text \zpageref{LastPage} 

\clearpage
TExt
\end{document}

Example of egreg:

\documentclass{report}
\usepackage{fancyhdr}
\usepackage{refcount,lastpage}
\fancyhead[R]{%
  \ifnum\getpagerefnumber{LastPage}=1\relax%
    \else
       Page \thepage\ of \pageref{LastPage}%
  \fi%
}
\pagestyle{fancy}
\begin{document}

Text 

\clearpage
TExt
\end{document}

@egreg: Sorry

Marco Daniel
  • 95,681
0

Here is a solution using the xstring package:

\documentclass{article}
\usepackage{lipsum}
\usepackage{refcount}
\usepackage{fancyhdr}
\usepackage{lastpage}
\usepackage{xstring}

\pagestyle{fancy}
\fancyhead{}
\fancyfoot{}
\fancyhead[R]{\IfEq{\getpagerefnumber{LastPage}}{1}{}{Page \thepage\ of \pageref{LastPage}}}

\begin{document}
\lipsum[1-3]
\end{document}
Peter Grill
  • 223,288