# Can I hook into the end of the document but *after* the \clearpage?

The code for \enddocument begins:

\def\enddocument{%
\let\AtEndDocument\@firstofone
\@enddocumenthook
\@checkend{document}%
\clearpage
\begingroup


I'd like to put something after that \clearpage. What's the simplest way to do that? Alternatively, I could put an extra \clearpage into the code that I want to dump there. Is there a problem with issuing more \clearpages than strictly necessary? And would it cause problems having a \clearpage before the \@checkend{document} (could there be interactions with other stuff using the end document hook)?

The specific use case is (with apologies to those who thought I might be asking a serious question) TikZ/PGF. As TeX processes a document with PGF stuff then it stores up some stuff that needs to be put at the start of the document. It does this with a token register \pgfutil@everybye which gets invoked with an \AtEndDocument{\the\pgfutil@everybye}. This works fine except if stuff is added to this list in the headers and footers of the last page - these don't seem to get added to the list in time to be added to the document (this came to light in looking at defining a fading-style directly in the fill command where the questioner wanted to define a fading in a header. There were various issues with this, and this appears to be a fairly important one.)

-
\def\foo#1\clearpage{#1\clearpage<your code>}\AtEndDocument{\foo}? – Martin Scharrer Apr 24 '12 at 20:42

The atveryend package provides

\AfterLastShipout{<code>}


From the documentation:

The code is called after the final \clearpage of \enddocument before the main .aux file is closed. This is the right place to remember the last page in the .aux file, for instance.

-

It's a bit hard to test without a concrete MWE, but if you insert \clearpage into \@enddocumenthook, the second \clearpage coming after that should have not effect.

Provided you're not adding anything after your own \clearpage which will cause an empty page to be produced.

If all else fails, you can patch \clearpage in \@enddocumenthook to put something after it.

A bit vague I confess, but one would really need a test example for anything more concrete.

-

The following seems to work (using test.tex):

\documentclass{article}
\AtEndDocument{%
\let\oldclearpage\clearpage%
\renewcommand{\clearpage}{%
\oldclearpage
}}
\begin{document}
test
\end{document}


As part of the test.log, showing that "your stuff" fits in before processing of test.aux is complete:

...
{c:/texlive/2011/texmf-var/fonts/map/pdftex/updmap/pdftex.map}]
stuff
(./test.aux)

-