[Tex/LaTex] Margin overflow when setting the geometry \AtBeginDocument

geometrymargins

Using the following minimal working example

\documentclass[12pt,a4paper]{article}

\usepackage[showframe]{geometry}
\geometry{hmargin={3.5cm,2.5cm}}

\AtBeginDocument{\geometry{vmargin={12cm,5cm}}}

\usepackage{lipsum}

\begin{document}
\lipsum[1-10]
\end{document}

Text on the first page overflows the lower margin. Other pages are fine, as illustrated by the figures below:

  • first page margin (overflown)

First page lower margin overflown

  • other pages (as expected)

Other pages are behaving correctly

I need to use commands in MWE for a complicated sequence (creating a complex template as a document class, calculating some lenghts involved in the template, then putting appropriate margins on the text block to fit into the template), so redefining MWE as an answer is probably not desirable.

Best Answer

You cannot use \geometry for a setting inside the text body. Use \newgeometry instead. However, fancyhdr should always be loaded after geometry.

\documentclass[12pt,a4paper]{article}

\usepackage[showframe]{geometry}
\geometry{hmargin={3.5cm,2.5cm}}

\AtBeginDocument{\newgeometry{vmargin={12cm,5cm}}}

\usepackage{fancyhdr}
\pagestyle{fancy}
\renewcommand{\headrulewidth}{0.0pt}
\renewcommand{\footrulewidth}{0.0pt}

\usepackage{lipsum}

\begin{document}
\lipsum[1-10]
\end{document}