# \thepage printing previous page number

I am trying to put a clickable icon beside my subsection so that the reader can click on it to visit the url related to that subsection. This url contains the page number, the subsection number, and the subsection title as parameters.

This is the code that I am using:

\subsection[My Dummy Subsection]{My Dummy Subsection \texorpdfstring{\href{\mybaseurl sn=\thesubsection &pn=\thepage &tn=My-Dummy-Subsection}{\icon{hreficon.jpg}} }{}}


This is working fine for most pages but for some pages the URL generated by the \href contains wrong page number. Specifically, \thepage is giving me the previous page number instead of the page number on which the subsection appears. I have observed that this is happening when the subsection is the first line on the page.

Any idea what is going on? How can this be fixed?

• \thepage does not necessarily refer to the page number where the command appears, because it is incremented only when a page is shipped out and, typically, TeX looks for more material than will fill a page before shipping out one. – egreg Jun 25 '18 at 15:55
• @egreg, thanks for the insight. so what do I do? – Priyshrm Jun 25 '18 at 16:07
• – Nicola Talbot Jun 25 '18 at 17:32

Since page numbering is tricky and based on how the page is constructed, it's best to use a \label and then \pageref to retrieve the exact page number. With that in mind, something like this:

\documentclass{article}

\usepackage{hyperref}

\begin{document}

\tableofcontents

% <some document content>

\section
[My dummy section]% ToC
{My dummy section \pageref*{sec:dummy_section}}% Title
\label{sec:dummy_section}

% <some more document content>

\end{document}


In some cases (when the label number of page reference changes) you'll have to compile twice before the correct reference is set.

• I think it would be an issue here to use it in the \href command? – Andreas Storvik Strauman Jun 25 '18 at 20:16
• @AndreasStorvikStrauman: hyperref provides a starred version that doesn't print a hyperlink but only the number. Otherwise you'd have a reference within a reference. – Werner Jun 25 '18 at 20:23
• Ooh. That's what the star is for! Got ya! – Andreas Storvik Strauman Jun 25 '18 at 20:24
• @Werner, thank you for responding. I tried to follow your suggestion with the following code: \subsection[Dummy Subsection]{Dummy Subsection \texorpdfstring{\href{\forum sn=\thesubsection &pn=\pageref*{sec:Dummy-Subsection} &tn=Dummy-Subsection}{\icon{hreficon.jpg}} }{}} \label{sec:Dummy-Subsection} But it is not working. Error message is : untitled-2.tex 132 TeX capacity exceeded, sorry [input stack size=5000]. <argument> \c@chapter l.132 ...mmy-Subsection}{\icon{hreficon.jpg}} }{}} – Priyshrm Jun 26 '18 at 3:24
• @Priyshrm: Try this paste. Instead of trying to expand the content inside \section, save the value of the page inside a counter first (using refcount). – Werner Jun 26 '18 at 4:16