Archive for the ‘typesetting’ Category

Controlling the page count in LaTeX

Sunday, October 11th, 2009

I’ve been working on a project which involves generation of simple books for print in LaTeX. The print shop set the requirement that the page count of the PDFs we give them always are multiple of four.

As this is something LaTeX doesn’t provide out of the box, my first idea was to do some post processing with the PostScript tools that you have on a Unix system. But introducing an extra tool wasn’t feasible at all: Running LaTeX from a webapp is fragile enough. Fortunately, LaTeX is just a module for TeX, and TeX is nothing but a programming language. So there most definitely is a way for doing this in plain TeX. Unfortunately, programming in TeX is everything but straight forward. Luckily I can’t resist language challenges…

And I did it! Here is my LaTeX macro that makes the number of pages in the document a multiple of some number:

The loop construct is the tricky part. It’s of the form

\loop
  ...
  \ifsomething...
  ...
\repeat

The if-statement in the middle controls whether we continue the loop or break out. Today, most people are probably more used to seeing the above logic written like this:

while (something) { .... }

A thing to note is that TeX-loops allow for statements to be run both before and after the if-statement is evaluated. Code before the statement is run in each iteration, similar to traditional do {} while (...) loops, but the code after is only run if the if-statement returns true:

\loop
  % Code to run in each iteration (do-while style)
  \ifsomething   %
  % Code to run if the if-statement above returned true (while-style)
\repeat

Finally, note that the if-statement must not have a closing \fi, as most if-statements in TeX have.

Tip: Finding material on programming in TeX is hard, but the TeXbook provides some help. Deep down in chapter 20 there are some examples of looping and conditionals, which proved to be enough for me.