[Tex/LaTex] How to keep the last page number even

double-sidedlastpagepage-breaking

I want to make sure the last page always be even, so I defined command as the following:

\documentclass{article}
\usepackage{lipsum}
\usepackage[paperwidth=302pt,paperheight=400pt, offset=0pt, hmargin=40pt, tmargin=50pt,
    bmargin=75pt, noheadfoot]{geometry}

\newcommand{\OpenNewPageIfNeeded}{%
\ifodd\value{page}%
\newpage%
\hbox{}%
\else%
\fi%
}
\AtEndDocument{\OpenNewPageIfNeeded}

\begin{document}
\lipsum
\end{document}

This works for most of the cases, but fails sometimes, for example the above sample code.

It seems that this question is duplicated with Ensure last page is even and blank, I tried the solution but it still fails, any suggestions?

Best Answer

Quoting the TeX FAQ:

[T]he output routine is asynchronous, and (La)TeX will usually process quite a bit of the “next” page before deciding to output any page. As a result, the page counter (known internally in LaTeX as \c@page) is normally only reliable when you’re actually in the output routine.

Solution: Use, e.g., the \ifthispageodd macro from KOMA-Script's scrextend package. Note that this macro uses a \label/\ref mechanism, so two LaTeX runs are needed for the correct output.

\documentclass{article}

\usepackage{lipsum}
\usepackage[paperwidth=302pt,paperheight=400pt, offset=0pt, hmargin=40pt, tmargin=50pt,
    bmargin=75pt, noheadfoot]{geometry}
\usepackage{scrextend}

\newcommand{\OpenNewPageIfNeeded}{%
  \ifthispageodd{%
    \newpage
    \null
  }{%
  }%
}
\AtEndDocument{\OpenNewPageIfNeeded}

\begin{document}
\lipsum
\end{document}
Related Question