This is not a question about solving a problem, because I already know how to solve it - several ways, in fact. It's more that I just want to understand what is going on.
Here is my code example, stripped down to the barest essentials.
\documentclass[a4paper]{article}
\setlength{\textwidth}{150mm}
\setlength{\textheight}{225mm}
\usepackage{graphicx}
\newcommand{\includePicture}[2]{\begin{center}\includegraphics[width=#1\linewidth]{#2}\end{center}}
\begin{document}
\section{First section}
Reference page \pageref{examplePicturePage}.
\section{Second section}
\includePicture{0.9}{example-image-10x16}\label{examplePicturePage}
\end{document}
This generates an undefined page reference, regardless of how many times the code is compiled (pdflatex). If the \textwidth
length is made one millimeter smaller, or the \textheight
is made one millimeter longer, the error goes away. Removing the \begin{centre}
and \end{centre}
in the command definition also make the error go away, in this case, regardless of the \textwidth
and \textheight
definitions (I put in 2mm for \textheight
, still no undefined reference.)
So I guess there is an overflow, when the included picture, formatted to the specified width, is too long to fit on the page. What I think is happening is, the overflow occurs while everything is being processed within the center environment. Then, the \end{centre}
closes that, and the processing continues onto a new page. But there is no content on the new page, nothing at all, except the \label
command. So this becomes a reference to a non-existent page. However, when the centre environment is removed, the \label
gets processed before we get pushed off to the second page.
The obvious solution to this is, don't put images that are too big for the page, but I just want to make sure my understanding of what is happening is correct. Is it?
Edited at the suggestion of Mico: The original example had no counter (the real-world document does, but I stripped it out); I have added section commands now to eliminate confusion about whether the issue is \pageref or \ref. In the current incarnation, the issue is essentially the same with either \pageref or \ref.
Edited at the suggestion of Torbjørn T. - example image used to make the file self-contained, with no need for other files.
BigPicture.pdf
. If I make it compilable, e.g., by specifying the optiondemo
while loading thegraphicx
package, the problem you describe goes away in the narrow sense of\pageref
producing the number1
. Of course, this masks a much bigger problem: you (a) haven't defined a suitable counter variable and (b) haven't provided a suitable method for incrementing the counter variable so that LaTeX can associate this counter with a\label
statement. Hence,\ref
statements must fail.example-image-10x16
instead ofBigPicture
. Theexample-image
images are included with themwe
package, which is part of TeX Live and MikTeX, so most people will have that image directly available.