# How to use \AtEndDocument with the class exam?

Using \AtEndDocument produces a new page with the class exam, if not put before \documentclass{exam}.

I made a package that modifies some key elements of the class, but the package needs to write something at the end of the document to work properly. To be precise, it uses \glsaddallunused from the glossaries package.

I've read on this very site that using \RequirePackage should work before \documentclass, but even using \RequirePackage to load the packages I use in my package, it yields a bunch of errors (including about some xkeyval package loaded before \documentclass):

Package xkeyval Error: xkeyval loaded before \documentclass. ...keyval loaded before \protect\documentclass}


How can I circumvent this to add stuff on what should have been the last page of my exam file?

• you could use etoolbox and add to the start of the end document hook so it comes before the clearpage even if used within your package see texdoc etoolbox section 3.3.2 Sep 30, 2020 at 20:28
• I didn't get the approach in section 3.3.2 to work with \AtEndDocument, but I found a solution in 2.6 : \AtEndEnvironment{document}{\glsaddallunused} which gives me the result I want. Sep 30, 2020 at 21:02

You just need to add the text before the class adds the page break to the same hook

\AtEndDocument{bar}
\documentclass{exam}
\begin{document}
foo
\end{document}

• Thanks a lot. You made me realized I already knew this… I was trying so hard to get my WE as minimal as possible that I forgot in the process some key elements of my problem. I will edit my question to clarify it. Sep 30, 2020 at 19:42

Thanks to the advice given by @DavidCarlisle, I was able to find a solution to my problem : loading the etoolbox package and using the \AtEndEnvironment{}{} function.

MWE :

\documentclass{exam}
\usepackage{etoolbox}
\AtEndEnvironment{document}{some text or command}
\begin{document}
foo
\end{document}