5

Is there a way to add page numbers to the PDF bookmarks?

Example:

\documentclass{article}
\usepackage{bookmark}

\begin{document}
\section{Section the First}
This is page 1.
\newpage
This is page 2.
\newpage
\section{Section the Second}
This is page 3.
\end{document}

enter image description here

1

Martin Scharrer's answer is a good starting point. However, the asynchronous output routine makes \thepage unreliable and requires the use of page labels.

\documentclass{article}
\usepackage{bookmark}
\usepackage{refcount}

% Section numbers in bookmarks (more important than page numbers)
\bookmarksetup{numbered}

\makeatletter

% Unique names for internal labels
\newcount\APTB@Count
\APTB@Count=\z@
\newcommand*{\APTB@LabelName}{APTB\the\APTB@Count}

% \label is a no-op inside the hook
\AtBeginDocument{\let\APTB@Label\label}

% The hook implementation for adding page numbers to bookmarks
\newcommand*{\APTB@AddPageToBookmark}{%
  % Set label and retrieve page number.
  \begingroup
    \global\advance\APTB@Count\@ne
    \APTB@Label{\APTB@LabelName}%
    \refused{\APTB@LabelName}%
    \protected@xdef\APTB@ThePage{%
      % \thepage is used as default, then the page number is at
      % least close.
      \getrefbykeydefault{\APTB@LabelName}{page}{\thepage}%
    }%
  \endgroup
  % Add page number to bookmark
  \edef\bookmark@text{%
    \unexpanded\expandafter{\bookmark@text}%
    \space(\unexpanded\expandafter{\APTB@ThePage})%
  }%
}

% Activate bookmark hook
\bookmarksetup{addtohook={\APTB@AddPageToBookmark}}

\makeatother

% Test
\usepackage{blindtext}
\begin{document}
\Blinddocument
\end{document}

There are already some PDF viewers that automatically show the page numbers in bookmarks. And the page numbers can easily be compared:

3

You can use the addtohook option of bookmark to change the bookmark text stored in \bookmark@text to add the page number (\thepage).

Note that I'm nut 100% sure if the page numbers are always correct as \thepage might be off if TeX needs to process a lot of text before it decides where to break the page. In this case an internal reference would be needed to get a correct page number on the second TeX run.

\documentclass{article}
\usepackage{bookmark}

\makeatletter
\bookmarksetup{addtohook={\edef\bookmark@text{\bookmark@text\space (\thepage)}}}
\makeatother

\begin{document}
\section{Section the First}
This is page 1.
\newpage
This is page 2.
\newpage
\section{Section the Second}
This is page 3.
\end{document}
1
  • Good starting point. I have extended it by using page references to deal with the asynchronous output routine. – Heiko Oberdiek Feb 28 '18 at 18:01

Your Answer

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