# Add page numbers to PDF bookmarks

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}


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
% Set label and retrieve page number.
\begingroup
\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

\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:

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