[Tex/LaTex] How to ensure document total page numbers is a multiple of four

calculationsconditionalspage-breaking

I'm producing a document (book class) that will ultimately be produced using offset lithography. It's therefore useful to ensure the total number of pages is a multiple of four by adding as many blank pages to the end as is appropriate.

This answer deals with adding a page if necessary to make the total number even. I can't figure out how to adapt it to deal with multiples of four. Is there a way?

Best Answer

\numexpr divisions round, so they are not so good in this case:

\documentclass{article}
\usepackage{refcount,lastpage}
\usepackage{kantlipsum}

\makeatletter
\newcommand{\checkmultipleoffour}{%
  \count@=\getpagerefnumber{LastPage}%
  \@tempcnta=\count@
  \divide\@tempcnta by 4
  \multiply\@tempcnta by 4
  \count@=\numexpr\count@-\@tempcnta\relax
  \ifnum\count@>0
    \pagestyle{empty}
    \loop\ifnum\count@<4
      \null\clearpage
      \advance\count@\@ne
    \repeat
  \fi
}
\makeatother

\AtEndDocument{\checkmultipleoffour}

\begin{document}

\kant[1-11] % for a 4 page document

% \kant[1-15] % for a 5 page document

\end{document}

The same in expl3 syntax:

\documentclass{article}
\usepackage{xparse}
\usepackage{refcount,lastpage}
\usepackage{kantlipsum}

\ExplSyntaxOn
\NewDocumentCommand{\checkmultipleoffour} { }
 {
  \prg_replicate:nn
   { \int_mod:nn { 4 - \int_mod:nn { \getpagerefnumber{LastPage} } { 4 } } { 4 } }
   { \thispagestyle{empty}\null\clearpage }
 }
\ExplSyntaxOff
\AtEndDocument{\checkmultipleoffour}

\begin{document}

\kant[1-11] % for a 4 page document

% \kant[1-15] % for a 5 page document

\end{document}

With \frontmatter and \mainmatter the situation is a bit more complicated.

\documentclass{book}
\usepackage{xparse}
\usepackage{refcount,lastpage,etoolbox}
\usepackage{kantlipsum}

\makeatletter
\patchcmd\mainmatter{\cleardoublepage}
  {%
   \clearpage\edef\@currentlabel{\number\numexpr\arabic{page}\ifodd\arabic{page}+1\fi\relax}%
   \label{LastFrontmatterPage}%
   \cleardoublepage
  }{}{}
\makeatother

\ExplSyntaxOn
\cs_new:Npn \egreg_int_coremainder:nn #1 #2
 {
  \int_mod:nn { #2 - \int_mod:nn { #1 } { #2 } } { #2 }
 }
\NewDocumentCommand{\checkmultipleoffour} { O{0} }
 {
  \prg_replicate:nn
   {
    \egreg_int_coremainder:nn { #1 + \getrefnumber{LastFrontmatterPage} + \getpagerefnumber{LastPage} } { 4 }
   }
   { \thispagestyle{empty}\null\clearpage }
 }
\ExplSyntaxOff
\AtEndDocument{\checkmultipleoffour}

\begin{document}

\frontmatter

\tableofcontents

\mainmatter

\chapter{A}

\kant[1-11]

\end{document}

The \checkmultipleoffour has also an optional argument where specifying possible pages before \frontmatter (an unnumbered frontispiece, for instance).

Note that a couple of LaTeX runs may be needed, because these macros require the \label-\ref system to synchronize.

Related Question