# \AtEndDocument causing spurious page break in exam class

Please see the MWE below. This is rather simple. The \AtEndDocument is causing a spurious page break before its execution. But the same code, when executed directly, does not cause this page break.

\documentclass{exam}

\AtEndDocument{%
\vfill
\begin{center}
\textsc{== End of Questions ==}
\end{center}}

\begin{document}

\begin{questions}

\question Test question 1

\question Test question 2

\end{questions}

% When inserted directly, it will not cause the page break

% \vfill
% \begin{center}
%   \textsc{== End of Questions ==}
% \end{center}

\end{document}


As Werner wrote, exam inserts code with \AtEndDocument too. With a current LaTeX you can define a rule, so that your enddocument code is before the code from the class:

\documentclass{exam}

\vfill
\begin{center}
\textsc{== End of Questions ==}
\end{center}}

\DeclareHookRule{enddocument}{myhook}{before}{exam}
\begin{document}

\begin{questions}

\question Test question 1

\question Test question 2

\end{questions}

% When inserted directly, it will not cause the page break

% \vfill
% \begin{center}
%   \textsc{== End of Questions ==}
% \end{center}

\end{document}

• Is \AddToHook alright? I am getting an undefined command error message. May 13 '21 at 16:27
• Oh, I need the lthooks package. May 13 '21 at 16:29
• No, further complications, LaTeX Error: Command \AtBeginEnvironment already defined. May 13 '21 at 16:30
• At I wrote: this require a current latex, and also all other packages should be up-to-date. You should not load lthooks separately. May 13 '21 at 16:45
• With older LaTeX you could more the \AtEndDocument before the \documentclass. But be aware that this won't work in a current LaTeX, there you really should use the rule declaration. May 13 '21 at 16:58

The exam class already adds a \clearpage via \AtEndDocument as part of the class loading (starting with line 1737 in exam.cls):

1737: \AtEndDocument{%
1738:   \clearpage
1739:   ...


While it doesn't print anything, the \clearpage is used to flush any remaining pages in order to calculate appropriate page references/counts. Since you issue an additional \AtEndDocument collection that is added after the \clearpage and prints content, it will reside on a new/separate page.