1

I am using longtable and want to access the page number from within the longtable, as in this bare-bone example:

\documentclass[a4paper]{article}
\usepackage{geometry}
\usepackage{longtable}

\begin{document}
\begin{longtable}{l}

longtable header: this is page \thepage
\endhead

A \\ 
A \\ 
A \\ 
... however many rows ...
... needed to exceed one page ...

\end{longtable}
\end{document}

However, the generated PDF always shows this is page 1 in the longtable header, even if it is on page 2.

According to a comment to this question, longtable "saves the head in a box and doesn't re-set it each page". The comment seems to suggest that the rolling page number simply cannot be accessed from within a longtable without a major rewrite. Do I understand that correctly? (I certainly hope that I do not understand it correctly, so there's still some hope that it can be done.)

  • 2
    Maybe this answer can help you :tex.stackexchange.com/a/157193/134144. Alternatively, you could use the supertabular pakage as described in this answer: tex.stackexchange.com/a/373987/134144. – leandriis Nov 20 '17 at 14:39
  • 1
    If you knew the name/register number of the box where the header is saved, you might be able to replace it globally using the afterpage package, but that seems like overkill. – John Kormylo Nov 20 '17 at 15:03
  • you do understand it correctly, you can refer to a page with \pageref in the body of the table but not in the head. (there is an answer on this site somewhere that has some fragile code that tries to work round this) – David Carlisle Nov 20 '17 at 16:15
  • or perhaps I didn't add any code, I think this is a duplicate of tex.stackexchange.com/questions/46205/… – David Carlisle Nov 20 '17 at 16:20
1

This sort of works. I can't figure out where the left margin comes from though. Also, for some reason the page counter wasn't working.

\documentclass[a4paper]{article}
\usepackage{geometry}
\usepackage{longtable}
\usepackage{everypage}

\newcounter{mypage}
\setcounter{mypage}{1}

\makeatletter
\AddEverypageHook{\stepcounter{mypage}%
  \ifdim\ht\LT@head>0pt
    \dimen0=\ht\LT@head
    \global\setbox\LT@head=\vbox to\dimen0{\strut
      longtable header: this is page \themypage}%
  \fi
}
\makeatother

\begin{document}
\begin{longtable}{l}
longtable header: this is page \thepage
\endhead
\rule{0.7\textwidth}{0.7\textheight}\\
\rule{0.7\textwidth}{0.7\textheight}\\
\rule{0.7\textwidth}{0.7\textheight}
\end{longtable}
\end{document}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.