LaTeX page layout parameters (Part 2)

In Part 1 of this tutorial we looked at the relationship between LaTeX’s page layout parameters and the conventional “DTP” layout model used by designers to parameterise page layout (refer to this diagram for a refresher). So, the next step is how do we use the formulae in Part 1 to do something useful? In this tutorial I will show one way to do this using a Lua script and LuaTeX.

LuaTeX: a primer
In future tutorials I will explain how to get started with a minimal LuaTeX setup but for present purposes I will have to assume that you have a working LuaTeX installation, perhaps via TeX Live, MiKTeX or something similar. In essence, LuaTeX is derived from, and extends, pdfTeX through the integration of Lua as an embedded scripting language and a whole host of additional functionality. It is the integration of the Lua scripting language which, in my opinion, makes LuaTeX so powerful and interesting. To run Lua code you use a LuaTeX command called \directlua{...} where ... is your Lua code. Through the \directlua{...} command you can execute your own Lua code and access the “LuaTeX API” which provides a huge range of libraries and functions that give you access to, and control of, many aspects of TeX’s internals through Lua code. This is an extremely simplistic overview, so should you want more information, grab a copy of the LuaTeX Reference Manual which is constantly updated as the LuaTeX program evolves. Note that the LuaTeX Reference Manual is a highly technical document which presents the APIs and libraries, it is not a user guide and is written by programmers for programmers.

Where are we heading?

The goal is to create a simple setup so that you can define custom pages and margins through LaTeX code such as this:

\documentclass[11pt,twoside]{article}
\input setpage
\setpage{300}{485}{250}{255}{5}{5}{5}{5}
\begin{document}
....
\end{document}

Where \input setpage inputs a file (called setpage.tex) which contains the macro to define a command called \setpage. This takes a number of arguments to define your custom page and margins. Of course, this should be wrapped up into a proper LaTeX package but that is left as an exercise for the reader.

So, what do we need to do?

  1. Create a Lua script that will perform calculations of the formulae presented in Part 1.
  2. Use \directlua{...} to run the Lua script in (1) via LuaTeX.
  3. Combine (1) and (2) into a very simple command (\setpage) you can use in your LaTeX document to define custom pages.

Create a Lua script

The starting point is, of course, that we want to have any size of paper with a document (book, business card etc) centred on the paper area. Because LuaTeX is based on pdfTeX it uses the parameters \pdfpagewidth and \pdfpageheight to set the width and height of the paper (i.e., the PDF page size). See the pdfTeX user manual for details. So, using \pdfpagewidth and \pdfpageheight we can set the size of the paper we want to use. Next, we need to know the page size of the document we want to produce. With the PDF paper size and document page size we can calculate the values of ΔX and ΔY to centre the document on our paper. The following SVG graphic (displayed via an iframe) shows the scenario we are aiming for.

So, our starting point is a set of page layout variables from the “DTP design world” which we will use to calculate the appropriate LaTeX page parameters. Our “DTP design world” parameters are:

  • PaperWidth = the value of \pdfpagewidth
  • PaperHeight = this is the value of \pdfpageheight
  • BookPageWidth = your document’s page width
  • BookPageHeight = your document’s page height
  • BookOuterMargin = BOM (refer to this diagram for a refresher)
  • BookInnerMargin = BIM (refer to this diagram for a refresher)
  • BookTopMargin = BTM (refer to this diagram for a refresher)
  • BookBottomMargin = BBM (refer to this diagram for a refresher)

Using the “DTP design world” values, we need to calculate the following LaTeX page layout parameters:\textwidth, \topmargin, \oddsidemargin, \evensidemargin and \textheight.

The following code shows one simple Lua script that will do the job. It defines a Lua function calcvals(arg) which has a single argument called arg . In Lua-speak arg is a table so that when we call the function calcvals({...}), the data in braces {...} is passed in as the value of arg and will contain a number of values which are accessed using the standard Lua method for accessing table values, such as arg.PaperWidth and arg.BookPageWidth. The code also sets some LaTeX parameters to 0 and defines “OneInch” as 25.4 – note that we are working with units in mm, just because it is convenient; hence 1 inch is 25.4 mm.

The most important point to note is the line

local marg = assert(io.open("path_to_your_tex_setup/margins.tex","w"))

We are creating a file called margins.tex which will define all the LaTeX parameters to achieve our preferred page layout. It will subsequently be input into our LaTeX document via TeX code such as \input margins.tex, hence you will need to output margins.tex into a location where the LuaTeX engine can find it.

Use \directlua{...} to run the Lua script

OK, at this point we have a Lua script which takes, as input, our “DTP design world” values and uses them to calculate, and write out, the LaTeX page layout values into a file called margins.tex. The next question is how do we get LuaTeX to run this Lua script? Answer, of course, \directlua{...}! Let us assume that the Lua code above is saved into a file called, say, code.lua.

loadfile(): a primer
At this point I need to briefly explain a Lua function called loadfile(). Quoting from the official documentation “… loadfile also loads a Lua chunk from a file, but it does not run the chunk. Instead, it only compiles the chunk and returns the compiled chunk as a function.” What this means is that calling loadfile(code.lua) does not actually execute the code in code.lua but compiles it and returns a function that you need to run in order to actually execute code.lua and so gain access to the calcvals(arg) function we defined in our Lua script. This may all sound a bit weird if you have not programmed in Lua but like most descriptions, it sounds more difficult that it actually is in practice.

Ignoring the LuaTeX side of things for the moment, concentrating just on Lua, to gain access to the function calcvals(arg) defined and stored in code.lua we have to

  1. run loadfile("path_to_your_tex_setup/code.lua")
  2. strictly speaking, make sure the code.lua loaded without error (check error return from loadfile(...))
  3. if successful, run the function returned from the call to loadfile("path_to_your_tex_setup/code.lua")

pagecalcs, loaderror = loadfile("path_to_your_tex_setup/code.lua")
-- you should check loaderror.
-- if pagecalcs == nil there was an error.
-- the error text will be in loaderror.
-- if pagecalcs is not nil, then code.lua compiled OK.
-- and will be in pagecalcs as function we can call as pagecalcs().

Assuming loadfile("path_to_your_tex_setup/code.lua") is successful, we can execute the returned function pagecalcs() which will enable us to use the calcvals(arg) function we defined and stored in code.lua.

Back to \directlua{...}

After the loadfile(...) detour we can now look at wrapping this up into something we can use with LuaTeX via \directlua{...}

As discussed, \directlua{...} is the command provided by LuaTeX which is, in effect, our “interface” or “gateway” to running Lua code from within a TeX document. The minimal LuaTeX code to run code.lua would be


\directlua {%
pagecalcs, loaderror= loadfile("path_to_your_tex_setup/code.lua")
pagecalcs()
}

And finally… \setpage

With no further ado, here is the LuaTeX code for setpage.tex. You’ll notice that \setpage takes 8 TeX parameters:

\def\setpage#1#2#3#4#5#6#7#8

which will be explained below.

The 8 parameters for \setpage#1#2#3#4#5#6#7#8 are passed straight into \directlua{...} so that our Lua function calcvals(arg) can use those 8 TeX parameters to do all the calculations, which result in the margins.tex file containing the LaTeX page parameters. This is where TeX meets Lua! The key thing to observe is the call to calcvals({...}). We mentioned earlier that when we defined calcvals(arg) in our Lua file code.lua that arg was a Lua table, now we can see this in action. The code in bold is the actual value of arg:


calcvals({
PaperWidth=#1,
PaperHeight=#2,
BookPageWidth=#3,
BookPageHeight=#4,
BookOuterMargin=#5,
BookInnerMargin=#6,
BookTopMargin=#7,
BookBottomMargin=#8
}
)

In addition, the definition of calcvals(arg) in our Lua file code.lua made calcvals(arg) return a number of values. Note that a nice feature of the Lua language is that it will return multiple values from function calls.

deltax, deltay, textwidth,topmargin,oddsidemargin,evensidemargin,textheight =
calcvals({PaperWidth=#1, PaperHeight=#2, BookPageWidth=#3, BookPageHeight=#4, BookOuterMargin=#5,
BookInnerMargin=#6, BookTopMargin=#7, BookBottomMargin=#8})

Why might we want to return those values? Well, if you look at code.lua carefully, you will see that it creates another table called pagevars and stores various page layout parameters in that table. The reason for doing this is to make the pagevars table available to other Lua scripts in our LuaTeX document. What we create is a Lua table which saves useful page parameter values we can use for other things, such as printers marks because we now have easy access to the necessary data.

pagevars={}
pagevars["paperwidth"]=#1
pagevars["paperheight"]=#2
pagevars["bookpagewidth"]=#3
pagevars["bookpageheight"]=#4
pagevars["bookoutermargin"]=#5
pagevars["bookinnermargin"]=#6
pagevars["booktopmargin"]=#7
pagevars["bookbottommargin"]=#8
pagevars["deltay"]=deltay
pagevars["deltax"]=deltax
pagevars["textwidth"]=textwidth
pagevars["topmargin"]=topmargin
pagevars["oddsidemargin"]=oddsidemargin
pagevars["evensidemargin"]=evensidemargin
pagevars["textheight"]=textheight}

Conclusion and example

To use all of this you will need to make sure that the TeX and Lua code is placed in locations where your LuaTeX executable can find them. In a future tutorial I will explain how to set up a minimal LuaTeX system on Windows (sorry, I don’t work on Linux or Mac). Here is a mimimal file demonstrating the use of \setpage

\documentclass[11pt,twoside]{article}
\input setpage
\setpage{300}{485}{250}{255}{5}{5}{5}{5}
\begin{document}
Hello Lua\TeX\
\end{document}

Looking back at our code for calcvals(arg)


calcvals({
PaperWidth=#1,
PaperHeight=#2,
BookPageWidth=#3,
BookPageHeight=#4,
BookOuterMargin=#5,
BookInnerMargin=#6,
BookTopMargin=#7,
BookBottomMargin=#8
}
)

we can see that \setpage is called with the following values (note: all assumed to be in mm!)

\setpage{PaperWidth}{PaperHeight}{BookPageWidth}{BookPageHeight}{BookOuterMargin}{BookInnerMargin}{BookTopMargin}{BookBottomMargin}

So, this is where we hoped to get to: using “DTP world” parameters to achieve the equivalent layout in LaTeX.

Example


\documentclass[11pt,twoside]{article}
\input setpage
\setpage{500}{500}{300}{300}{10}{10}{10}{10}
\begin{document}
\pagestyle{empty}
Hello Lua\TeX
\end{document}

Here is the PDF document output by LuaTeX but note that the printers marks code is not included in this example, that’s for another day!

LaTeX page layout parameters (Part 1)

Powered by MathJax

I’m using MathJaX to display the formulae in this post because I need some practice with using it, so please excuse this indulgence. Do give comments or feedback on whether you are able to read everything. Again, you can right-click over the formulae to display the MathJaX menu which will let you zoom the formulae for easier reading.

Introduction

LaTeX’s facilities for typesetting are truly superb but I don’t think it’s an understatement to say that the parameters controlling page layout are confusing – actually, they are very confusing and trying to achieve custom layouts can be quite frustrating. There are of course some excellent LaTeX packages, such as geometry.sty, which help you set page layout parameters but if you prefer have greater control, then this is the post for you. To get the most from this post, I suggest you grab a copy of the accompanying diagram (in SVG) which shows everything in much more detail.

On TeX, LuaTeX, LaTeX, pdfTeX, XeTeX…

If you are fairly new to “the TeX world”, it can be quite difficult to understand the differences between what appear to be so many “different types of TeX”. I’ll try to explain this, albeit briefly, and with due apologies to expert readers who would be right to say that this is not the whole story. The true, original TeX invented by Donald Knuth, is a typesetting program which understands a number of fundamental (i.e., very low-level or “primitive”) commands, which are built into the executable program. Using these low-level commands you can write so-called macros to combine them into “higher level” commands to do useful things, and so create macro packages which provide end-users with a set of tools to create documents. Very large macro packages have been written which provide a rich set of commands to control document typesetting. LaTeX is one such “very large macro package”.  To use a macro package, such as LaTeX, you need to process your document with an executable program to generate the typeset output. This “executable progam” is referred to as a “TeX engine”: it runs and executes your document plus the LaTeX macros to generate the typeset result. Over the years, the original TeX engine created by Knuth has been extended and enhanced to add new features and these newer engines are required to be given names which distinguish them from Knuth’s original application. Examples of newer TeX engines include pdfTeX and the very latest engine LuaTeX. So, it is important to distinguish between the name of a large macro package (e.g., LaTeX) used to write/prepare documents and the executable “TeX engine” used to process those documents: pdfTeX, LuaTeX, XeTeX and so forth. You may see people write, for example, “I am running LaTeX using LuaTeX” and that’s a nice way to clarify the difference.

I hope this helps more than it confuses!

Assumed setup

To put this into context, suppose you are using a vanilla flavour LaTeX document class, such as article.cls, and you want to input some LaTeX code to control the layout, as follows:

\documentclass[11pt,twoside]{article}
%input some LaTeX code to control the layout
\begin{document}
......
......
\end{document}

Hopefully, by the end of this mini-tutorial series you will be able to calculate and set the appropriate LaTeX parameters to create any custom page size you wish.

Problem definition

Suppose that you want to typeset, say, a book (or any other document type, e.g., business card) which has a certain page width and page height, and you would like to typeset and layout the book such that when you print out the pages (e.g., for proofing), the book pages will be horizontally and vertically centred on your paper (which can be any size, too). This is the usual situation when printing designs from commercial applications such as Adobe InDesign or Quark Xpress. The same can easily be achieved with LaTeX using just a few simple formulae to calculate the appropriate parameters. Note that adding “crop marks” (or “printers marks”) is not covered here.

There are, of course, LaTeX packages to do this for you but if you want to have access to the full details, the following formulae will give you a great deal of control and allow you to write your own tools, e.g., in Perl, Lua etc. We will implement the following in Lua code and integrate it into LuaTeX via a very simple package.

Because LuaTeX is derived from pdfTeX it also uses the \pdfpagewidth and \pdfpageheight commands to set the width and height of the PDF page.

Some definitions

\[\begin{aligned}
\mathrm{B_{PW}}& =\mathrm{\mbox{width of the book page}} \\
\mathrm{B_{PH}}& =\mathrm{\mbox{height of the book page}} \\
\mathrm{B_{OM}}& =\mathrm{\mbox{the Book Outer Margin}} \\
%; i.e., the outer white space margin between the edge of the book page and the start of the text area
\mathrm{B_{IM}}& =\mathrm{\mbox{the Book Inner Margin}} \\
%; i.e., the inner white space margin between the spine (fold) of the book page and the start of the text area}\\
\mathrm{B_{TM}}& =\mathrm{\mbox{the Book Top Margin}} \\
%; i.e., the top white space margin between the edge of the book page and the start of the text area}\\
\mathrm{B_{BM}}& =\mathrm{\mbox{the Book Inner Margin}} \\
%; i.e., the bottom white space margin between the edge of the book page and the start of the text area}\\
\end{aligned}\] \[\begin{aligned}
\Delta \mathrm{X} & =\frac{1}{2}(\mathrm{pdfpagewidth} – \mathrm{B_{PW}})\\
\Delta \mathrm{Y} & =\frac{1}{2}(\mathrm{pdfpageheight} – \mathrm{B_{PH}})\\
\end{aligned}\]

If you follow this diagram you should see that the following formulae can be used to calculate the LaTeX parameters such that your desired book page is centred horizontally and vertically on the PDF paper area. Note that although I use the term “book” you can use these formulae to centre any document type/page within a larger PDF document area (see PDF samples, below).

Formulae for the width of the PDF page

  • Starting with left-hand (even-numbered book pages)
\[\begin{aligned}
\mathrm{pdfpagewidth} & = \Delta \mathrm{X} + \mathrm{B_{OM}} \\
& + \mathrm{marginparwidth} \\
& + \mathrm{marginparsep} \\
& + \mathrm{textwidth} \\
& +\mathrm{B_{IM}}+ \Delta \mathrm{X}
\end{aligned}
\]

and

\[\begin{aligned}
\mathrm{pdfpagewidth} & = \mathrm{1 inch} + \mathrm{hoffset}\\
& + \mathrm{evensidemargin} \\
& + \mathrm{textwidth} \\
& +\mathrm{B_{IM}}+ \Delta \mathrm{X}
\end{aligned}
\]
  • For right-hand (odd-numbered book pages)
\[\begin{aligned}
\mathrm{pdfpagewidth} & = \Delta \mathrm{X} + \mathrm{B_{IM}} \\
& + \mathrm{textwidth} \\
& + \mathrm{marginparsep} \\
& + \mathrm{marginparwidth} \\
& +\mathrm{B_{OM}}+ \Delta \mathrm{X}
\end{aligned}
\]

and

\[\begin{aligned}
\mathrm{pdfpagewidth} & = \mathrm{1 inch} + \mathrm{hoffset} \\
& + \mathrm{oddsidemargin} \\
& + \mathrm{textwidth} \\
& + \mathrm{marginparsep} \\
& + \mathrm{marginparwidth} \\
& +\mathrm{B_{OM}}+ \Delta \mathrm{X}
\end{aligned}
\]

Formulae for the height of the PDF page

\[\begin{aligned}
\mathrm{pdfpageheight} & = \mathrm{1 inch} + \mathrm{voffset} \\
& + \mathrm{topmargin} \\
& + \mathrm{headheight} \\
& + \mathrm{headsep} \\
& + \mathrm{textheight} \\
& + \mathrm{footskip} \\
& +\mathrm{B_{BM}}+ \Delta \mathrm{Y}
\end{aligned}
\]

and

\[\begin{aligned}
\mathrm{1 inch} + \mathrm{voffset} + \mathrm{topmargin}= \Delta \mathrm{Y} + \mathrm{B_{TM}} \\
\end{aligned}
\]

In Part 2 I’ll show how to use these formulae via some examples, but till then here are some random demos (PDFs) of the formulae in action.

  1. Demo 1
  2. Demo 2
  3. Demo 3