3

I am trying to set the page counter of docB.tex based on the page of docA.tex that contains the label my-label. I'm using the packages xr-hyper and hyperref based on this example.

docA.tex

\documentclass{article} 
\usepackage{xr-hyper} 
\usepackage{hyperref} 
\begin{document}
    Here is a label. \label{my-label}
    It appears on page \pageref{my-label}.
\end{document}

docB.tex

\documentclass{article}
\usepackage{xr-hyper}
\usepackage{hyperref}
\externaldocument[A-]{docA}
\begin{document}
    In docA, the label appears on page \pageref{A-my-label}.
    Set the page number to that: 
    \setcounter{page}{\pageref{A-my-label}}
\end{document}

I compile docA.tex twice for good luck, and it correctly produces a PDF that says

Here is a label. It appears on page 1.

However, when I compile docB.tex I get the error

./docB.tex:8: Missing number, treated as zero.
<to be read again> 
                   \protect 
l.8 ...    \setcounter{page}{\pageref{A-my-label}}

I know the cross-referencing works correctly because if I comment out the \setcounter line, then line 6 correctly prints the page number. So the error comes from within the \setcounter call.

What am I missing?

  • 1
    \pageref can not be used to set a counter even on a later pass, as it can have formatting commands or be in roman or whatever, and is made robust with an internal \protect that you see in the error message. You can use the zref packages to give a version of page ref that can be used in that way and defaults to 0 so it is always a legal number. – David Carlisle Dec 15 '16 at 23:11
  • \mbox{1} would also print as 1 but not work in \setcounter{page}{\mbox{1}} for similar reasons. – David Carlisle Dec 15 '16 at 23:13

1 Answers1

3

The problematic line is:

\setcounter{page}{\pageref{A-my-label}}

Package hyperref adds a link and a link is not a number that can be used with \setcounter. Package refcount helps to extract the number from the reference:

\setcounterpageref{page}{A-my-label}

If the label is not yet defined, the default value 0 is used. The default can be changed by macro \setrefcountdefault. Example:

\begingroup % keep default change local
  \setrefcountdefault{1}%
  \setcounterpageref{page}{A-my-label}% global assignment
\endgroup
Heiko Oberdiek
  • 271,626
  • Thanks! Just to clarify, I added \usepackage{refcount} above \usepackage{xr-hyper} in both files and replaced the \setcounter line with the \setcounterpageref line you provided. – ConvexMartian Dec 15 '16 at 23:57