Polishing for Print

This is an excerpt of the book “Better Books with LaTeX.” The book comes with a LaTeX template you can use to easily create your own books.

While using LaTeX can save you a lot of time by automatically formatting each page, it has its limits. For example, you might end up finishing a section or chapter with one line that ends up alone on a page. This is ugly but it is nothing LaTeX can do anything about. The program’s hands are tied because it cannot rewrite the text for you. It will display every line—even if the final line in a chapter is “orphaned.”

Let us now look at a checklist you should go through before releasing the book (and after you have completed all the texts, indexes, bibliography, etc.):

 Clean up Empty Space

Skimming through a book and seeing large unused white spaces is a telltale sign of an unpolished book. Do not be tempted to add a photo of your cat or some meaningless diagram just to fill the empty spaces. In addition, it is literally a waste of space and ultimately of book pages (affecting printing costs, weight, shipping costs, etc.). Depending on your contents, it is possible to save a dozen pages by cleverly arranging your text. While LaTeX provides some functionality by automatically arranging images, you do not want to end up in a situation where the image is far from the position in the text where it is referenced. Most of the time, you want the image to show up exactly where it should be (the default setting of the template). Likewise, enforcing page breaks and having sections starting on the right side can lead to a number of empty pages. Let us examine a number of items to look out for:

  • Combining paragraphs. If you need to save space, you can combine two closely related paragraphs into one large paragraph. While this might come at the cost of some readability, it is very easy to implement.
  • Breaking paragraphs. On the other hand, if you need to fill white space, be more generous with starting new paragraphs. This reexamination of your text might actually improve readability by splitting it into smaller parts.
  • Shortening sentences. If your paragraph spans to the next page due to just a few words, shortening your text might be the best way to clean it up. The downsides are the additional editing work as well as ending up with the same problem should the previous text happen to increase in size.
  • Rearranging images. You can play around with moving an image before or after a paragraph and check if this solves the problem. For example, if you have a paragraph followed by white space followed by a picture on the next page, you could simply switch the picture with the paragraph, ending up with half of the paragraph on the first page and half on the second page, saving you space and eliminating unused white space.
  • Resizing images. Besides simply rearranging images, you can also limit or increase their size by either changing the limits of the \adjustbox{} command or by making the image itself smaller or larger. Be advised that using \adjustbox should be the last resort. While scaling photographic images is no problem, any image containing lines, tables, etc. will end up not looking good. Also, you should take extra care to have all your images share the same font sizes. A better option for vector graphics is to change the actual graphic, for example by reducing the distance between boxes in a diagram.
  • New page. Sometimes you want to add a blank page or have the next section start on a new page. For example, you have a section starting at the lower right page, with just half a paragraph fitting on that part of the page. Here, it is best to move the whole section to the next page and fill the empty space as discussed above. You can do that by simply adding \newpage (or \blankpage if you want to finish the current page and add an empty page).

As each change will possibly affect subsequent pages, you have to check the results page by page from front to back. When moving things around, take special care to have images near their references in the text—and to have a reference for every single image! The best experience for the reader in regard to the images is if he or she does not need to browse back and forth to connect what you write about the particular image and the image itself.

If you encounter any “lost lines” (single lines that are put on the next page although they could fit on the current one), try adding a \newpage command at the end of the paragraph. This is an issue that sometimes occurs with the LaTeX compiler.

Left Hand / Right Hand Pages

When you have cleaned up your empty white spaces, you should again preview your entire PDF file. For this, you can either use Amazon’s online previewer or a prepared PDF file in your PDF reader.

For the latter, I use Adobe Acrobat Reader DC (, load the generated PDF file, select “File” / “Print…,” select “Microsoft Print to PDF,” and select pages “ii – (your last page).” By moving the second page to the first page, we can now open the new file and switch to “View” / “Page View” / “Two Page View” and are now able to look at both pages exactly how they would end up in the printed book, with the even page numbers on the left, and the odd page numbers on the right.

Now, go through the entire book again to double-check whether the chapters and sections start on the correct side of the book.

 Clean Up Graphics

To understand graphics in the book production process, you have to understand file formats. In principle, there are three types of image files:

  • Vector graphics. Vector graphic files like EPS or PDF contain code to actually draw the picture in question. This code is understood even by the printer itself, which can help to improve the print quality tremendously. Imagine how much better a printer can deal with the information “draw a line from A to B” as opposed to “draw pixel to position 35/20, 36/21, 37/22, …” Use these file formats whenever possible. TikZ graphics produce vector graphics, and stock image sites like offer many files both as normal images files as well as vector graphics. Both EPS and PDF files will work, although PDF files are the preferred format because P is also your output format. They do not need to be converted but can be embedded directly into the final PDF by LaTeX.
  • Lossless PNG images. PNG images undergo a compression algorithm, but the type of compression used does not cause any loss of quality—the resulting PNG image has the same exact image information as the original picture. If you do not have vector graphics available, use PNG files.
  • Lossy JPG images. The limiting factor of e-books is the total file size; the limiting factor for printed books is the number of pages. JPG images are optimized for size, so if possible, do not use JPG files for any graphic in your printed book. As image size is not an issue in print, it’s better use lossless PNG images if you have them available.

resolutionuseuse it with

Lossy JPG300-600dpie-booksphotos

Lossless PNG600dpiPDFphotos, diagrams

Vector graphicsn/abothgraphs, diagrams

Figure 8.1:Comparison of graphic formats and their application.

With this in mind, examine the images you are using now and maybe try to find better versions of those images or replace them with vector graphics (we can help you with that, see Chapter 3.8). For lossless and lossy images, choose a resolution of 600 dots per inch, as printers usually use this resolution for black on white printing.

Gimp   Gimp is a free graphics editor ( with which you can create, scale, or convert images.

Gimp can show you the resolution, but you can easily calculate it yourself. Simply take the width of your picture in pixels (e.g., 1245) and divide it by the width of your page in inches (e.g., 4.15”, which would result in 300 dots per inch).

Please note that when scaling JPG and PNG files in Gimp, you can also scale the DPI resolution. For example, a 1245 pixel wide image with 300 dpi will appear smaller than a 1245 pixel wide image with 100 dpi.

To calculate the whole width of a page in your book, take a look at your settings in lib/bookformat.tex:

\usepackage[paperwidth=5.25in, paperheight=8in, inner=0.80in, outer=0.3in, top=0.7in, bottom=0.5in]{geometry}

The space where you can actually put text is paperwidth – inner – outer. In this case, 5.25in – 0.8in – 0.3in = 4.15in. With a desired resolution of 600 dots per inch, you need an image with a width of 4.15in * 600 = 2490 pixels.

Lightshot   Lightshot is a free screenshot utility (see that saves the entire screen or parts of it into an image file at the press of a button.

One problem I faced with the screenshots in this book is that (at least with Lightshot) images are saved at 120dpi. If I include them directly into the book, they will look pixelated and way too large. Opening the image in Gimp, selecting Image / Scale Image, and changing the X/Y resolution from 119.990dpi to 300dpi does the trick.


Converting LaTeX to HTML

This is an excerpt of the book “Better Books with LaTeX.” The book comes with a LaTeX template you can use to easily create your own books.

Now that you know how to fill the template, let us take a look at how to activate certain content only for the HTML or only for the PDF output. Afterward, we will examine the technical details of converting LaTeX to HTML, and how to add that capability to an existing project that does not use the template. If you plan to only use the template, feel free to skip section 7.2.

pdfLaTeX   pdfLaTeX is a basic LaTeX typesetting engine that translates LaTeX documents directly into PDFs or HTML files (with the help of tex4ht).

XeLaTeX   XeLaTeX is a LaTeX typesetting engine with an extended font, as well as UTF-8 encoding (for special characters) support. It is slower than the more basic pdfLaTeX.

tex4ht   tex4ht is a tool to translate LaTeX code into a HTML document.

To convert LaTeX to HTML, we need a special compiler, tex4ht. Unfortunately, tex4ht does not work with the default compiler we have set up for the Overleaf project. It only works with pdfLaTeX, not with XeLaTeX or LuaLaTeX. So, in Overleaf , we have to click on the settings icon and select pdfLaTeX as the LaTeX engine. Let it compile, then clear the cache, and have it compile again. If you did not use the template, you might run into some compatibility problems between XeLaTeX and pdfLaTeX. If it is already compatible or if you are already working with pdfLaTeX, you can skip the chapter after the following section 7.1.

  Switching from XeLaTeX to pdfLaTeX

If you are experiencing problems after switching a XeLaTeX project to pdfLaTeX in the project settings, an adaption of the LaTeX code is necessary. As we do not want to make the original XeLaTeX code unusable, we need to add conditional statements. For this, you need to include the ifxetex package:


Then, simply surround XeLaTeX-specific code (or simply code that produces an error) with a “\ifxetex …\else …\fi” construction. Having this compatibility allows you to generate PDF files with XeLaTeX, and also produce HTML documents with pdfLaTeX when you switch compiler settings.

For example, when generating an HTML file, you cannot include PDF files or vector graphics. Instead, you have to rely on JPG and PNG image files. Another application would be if you want to minimize the size of an existing image file for an e-book. A code might look like this:

\adjustbox{max width=.95\columnwidth, max height=.4\textheight}{ 

Yet another example is using different texts for the PDF (designed for print) and the HTML output (designed for an e-book release). The conditional clause allows you to show medium specific text, dates, or formatting:

2016, First Edition 
\textsc{ISBN} 978-3-945586-21-1 
Printed on acid\hyp{}free, unbleached paper. 
Ebook created \today 
\textit{PS: If you want to rate this book, please always add a short text comment. Did you like it? What can be improved? Who would you recommend it to? Without a text comment, your star rating will not be counted on the Amazon website!} 

A further example is footnotes. As e-books do not have pages in the traditional sense, your footnotes would end up in a separate part of the book at the end with a small reference. Given that we do not want the reader to jump back and forth, one approach is to simply include the footnote in parentheses if the output is not set to XeLaTeX (print):

A popular assumption is that the same words convey the same meanings. This is generally only correct if both conversation partners belong to a common \emph{language network}, i.e., that they define their terms either among themselves or through close acquaintance\ifxetex.\footnote{Interesting\else~(interesting\fi~to note here is the theory that every person in the world is connected to every other person by approximately seven intermediate connections\ifxetex~\citep[cf.][]{Travers69anexperimental}.}\else, \cite[cf.][]{Travers69anexperimental}).\fi{}

The last example is handling references. In a printed book, you can add a quotation page at the end to list the sources of individual quotes. This is possible because you can quickly jump to the end of the book and back using a page number, while in an e-book, you have no fixed page numbers and have to rely on links:


  Tex4ht Configuration

If you plan to use the template, feel free to skip this section.

tex4ht   tex4ht is a tool to translate LaTeX code into a HTML document.

On the Overleaf platform, no separate installation for tex4ht is needed. All you need to do is include it in your workflow. In Overleaf , this is done by adding a file named “latexmkrc” in the main directory (and thus overriding the default Overleaf one) of your project and adding a configuration file.

Figure 7.1:Build chain using different tools to produce different output formats.

latexmk   latexmk is the build tool Overleaf uses to automatically build your LaTeX project. The configuration file latexmkrc can be used to override build settings or add a hook to another compiler (like tex4ht to generate HTML output in addition to the PDF).

First, let us create the latexmkrc file in the main directory of your project and insert this code (depending on your project, if you are not using the template, you might need additional settings from

$pdflatex = "htlatex %S \"htlatex.cfg,MyFonts,NoFonts\" \"\" \"\" -shell-escape > output.txt; pdflatex -synctex=1 %O %S";

This creates a hook in the compilation chain of LaTeX (LaTeX calls $pdflatex at the end of the compilation). All this does is call htlatex before calling pdflatex, giving you an HTML output in addition to the PDF output. It also writes the output of the compilation of htlatex to a new file called output.txt to be used for debugging.

When all compiles, the HTML and debug files will not show up within Overleaf . Instead, you have to actually download the output files (use the drop-down menu at the bottom left in the project window, “DOWNLOAD AS ZIP” and “Input and Output Files”). There, you should check if there is an HTML file in the main directory. That is your converted LaTeX document! You can now easily copy and paste the whole document or parts of it into, for example, a WordPress post and publish it online.

If there is no HTML file, double-check for any errors within Overleaf and check the output.txt. If you cannot make sense of it, just let us know, we can help!

Converting that HTML file into a real e-book format like MOBI, or EPUB takes some extra effort as we need to adjust the settings, take care of the table of contents, add a cover, and optimize our images. We will go over this in Chapter 8.

  HTML Output Formatting

Unfortunately, tex4ht cannot do a 1:1 conversion simply because printed books are based on pages while HTML documents and e-books are continuous texts. Also, formatting, spacing, and images are handled differently, so we need to configure this separately. In the listing above, you can see a reference to htlatex.cfg—that is where the tex4ht configuration resides:

\Configure{DOCTYPE}{\HCode{<!DOCTYPE html>\Hnewline}} 
\Configure{@HEAD}{\HCode{<!-- for beautifying --><link rel="stylesheet" type="text/css" href="site.css" />\Hnewline}} 
% Translate \textbf, \textit and \texttt directives into <strong>, <em> and <code> 
\Configure{textsc}{\ifvmode\ShowPar\fi\HCode{<span class="sc">}}{\HCode{</span>}} 
% Translate verbatim and lstlisting blocks into <pre> elements 
\ConfigureEnv{minipage}{\ifvmode\IgnorePar\fi\HCode{<div class="minipage">}}{\ifvmode\IgnorePar\fi\HCode{</div>\Hnewline}}{}{}% 
% Do not set ‘indent‘/‘noindent‘ classes on paragraphs 

What the file does is configure the mapping between LaTeX and HTML. If you are familiar with HTML, you see that you can configure the contents of the output HTML file with the htlatex.cfg file. It starts with setting up the HTML header and then configures how individual LaTeX commands (emphtextbf textit, …) should be translated into HTML. For example, text formatted in italics (textit) is translated into HTML by using the emphasis HTML tag (¡em¿). The 
 command directly inserts HTML commands in the output file and can also be used in the normal LaTeX files. For example, you can use HCode< hrstyle = ”clear : both”∕ > to directly add a vertical line into the HTML output file and thus the e-book.

CSS   CSS files determine the final design of appearance of a website (or e-book).

Also, in the htlatex.cfg file, the site.css file is referenced. This can be adjusted according to your needs, although in my experience, some of the following settings work nicely for Kindle e-books:

1. You might want to adapt the sizes of the chapter title and section title fonts:

.chapterHead { font-size: 1.5em; margin-top: 0.83em; margin-bottom: 0.83em; font-weight: bold; text-align: left; } 
.sectionHead { font-size: 1.17em; margin-top: 1em; margin-bottom: 1em; font-weight: bold; } 
.subsectionHead { margin-top: 1.33em; margin-bottom: 1.33em; font-weight: bold; } 
.subsubsectionHead { font-size: 0.83em; margin-top: 1.67em; margin-bottom: 1.67em; font-weight: bold; }

2. In Kindle e-books, new paragraphs have indents on the first line. If you do not like that, this is the workaround:

p { margin-top: 1em; margin-bottom: 1em; text-indent: 0.01em; }

3. One way to highlight a quotation:

.quotation { margin: 0.25em 0; padding: 0.35em 40px; line-height: 1.45; position: relative; color: #383838; } 
.quotation:before { display: block; padding-left: 10px; content: "\201C"; font-size: 80px; position: absolute; left: -15px; top: -20px; color: #7a7a7a; } 
.quotation cite { color: #999999; font-size: 14px; display: block; margin-top: 5px; } 
.quotation cite:before { content: "\2014 \2009"; } 
div.quotation { width: auto; }

4. Adding small capitals textsc:

.sc { font-variant: small-caps; }

5. Have description list elements printed in bold:

dt.description { font-weight: bold; }

Template Management

This is an excerpt of the book “Better Books with LaTeX.” The book comes with a LaTeX template you can use to easily create your own books.

Previously, we have covered mainly the chapter folder main, the front folder, and the back folder. Now we will discuss those folders again in more detail and go through the remaining folders. This will help you to know where the configuration for each part of the template lies and allow you to make changes.

  Template Library Files

Let us first focus on the lib directory. There, each file is a set of new commands or configurations to set up the style and contents of your book.

  Packages File

The lib/packages.tex file loads all the libraries in the directory and loads and sets up additional packages, depending on the output format. The first two commands load the nag package to provide additional warnings if you are using outdated or invalid packages, and expand the output of error messages (\errorcontextlines 1000) in the log file to help you fix issues more quickly.

The ifxetex package loads a small script that we can use to check whether the target platform is a printed PDF (with XeLaTeX) or an HTML file (with pdfLaTeX). It follows the basic format of “\ifxetex(executed if XeLaTeX is used) \else (executed if pdfLaTeX is used) \fi.”

Think of \ifxetex as the main junction between the e-book (the HTML file output using pdfLaTeX) and the print book (the PDF file output using XeLaTeX).

Next are a number of packages and configurations specific for either of those platforms. The adjustbox packages adjust figures to fit onto a page—a feature needed only for the printed PDF as e-books automatically adjust graphics depending on the reader. The psvectorian package allows us to add curly horizontal lines at the end of sections and chapters—a feature not supported by e-books. The next command, \hrule, is not supported by tex4ht, so we create a specific command, \myrule, and translate it into a HTML ¡hr /¿ command correspondingly. For the em dash, we need to add spaces (even if it is just 0) left and right of it to allow for line breaks. For the HTML output, we simply use the ASCII code for the em dash (#8212;).

At the end of the file, all relevant packages of the lib directory are loaded, so we only need to include lib/packages.tex to load the whole configuration. On the following pages, I will discuss each package.

 Language Selector

In an Overleaf project, you can select the language by making either german.tex or english.tex the main file. In the file, either the command \babelDE or \babelEN get activated by the command “\usepackage[ngerman]{babel}” or “\usepackage[american]{babel} respectively. The command sets “\languagename” either to “ngerman” or “american.” In lib/languageselector.tex, the new command “\babelDE{content}” checks whether “ngerman” is set, and then displays the content. If it is not set, nothing is displayed. Likewise with the “\babelEN{content}” command, resulting in only one of the languages being displayed. The first use of this command can be seen at the end of the file, where we overwrite the naming of the table of contents depending on the language we have selected.

If you want to add a different language, simply add a new empty TEX file in the root directory (for example, spanish.tex), copy and paste the contents of english.tex into that new file, and replace “american” with “spanish.” Next, add the following commands in lib/languageselector.tex and you are ready to use “\babelES” as a command in your text.

\newcommand{\babelES}[1]{\ifnum\pdfstrcmp{\languagename}{spanish}=0 {#1}\fi} 


Let us start with lib/bibliography.tex. This adds the bibliography feature to the document and (due to compatibility issues) either loads biblatex or natbib depending on whether you use XeLaTeX or pdfLaTeX. In addition, it loads the actual bibliography file from the bibliography directory, depending on the language you have set up.

The parameters of loading biblatex determine what citations look like. There are numerous possible combinations of the author name, the year of publication, and the title, each with different degrees of detail and verbosity. The setting authortitle in my template replaces citations with the author name followed by the title. Without the setting, the default would be a simple number that is referenced again at the back of the book in the bibliography.

At the end, the file also loads the nameref library. With it, you can reference the label of a chapter or section and get the chapter or section title in return. Instead of just referencing an abstract chapter number, adding the title helps the reader to know what you are talking about. In addition, any changes of the referenced chapter or section title are automatically synchronized.

For example, look at this code:

\chapter{My First Chapter}\label{c1_myfirstchapter:sec} 
Yesterday, I bought a car. 
\chapter{My Second Chapter}\label{c2_mysecondchapter:sec} 
In chapter ‘‘My First Chapter,’’ we have talked about buying a car.

If we changed the chapter title “My First Chapter” to “How I Bought My Car,” we would have to update the reference in the second chapter. With the \nameref{} command, this is no longer necessary:

\chapter{My First Chapter}\label{c1_myfirstchapter:sec} 
Yesterday, I bought a car. 
\chapter{My Second Chapter}\label{c2_mysecondchapter:sec} 
In chapter~\ref{c1_mychapter:sec}, we have talked about buying a car.

As we will later discuss in Chapter 13, it is important to prevent duplication of text whenever possible because the larger the document gets, the harder is to apply non-breaking changes. If you have to search through the whole document every time you apply a change, your project will take much longer than necessary.

 Book Format

Next in line is lib/bookformat.tex. The first thing you notice is the long list of usepackage commands with the one marked with 5.25” x 8” uncommented. Here is your choice of how large your book should be. This of course applies only to a printed version of your book. For e-books, the size of your book is determined by the device your reader will use.

Personally, I like 5.25” x 8”, but it is totally up to you. Look at your personal library (and take a ruler) and check out the different formats. Besides personal preference, the only thing to keep in mind is that smaller formats lead to more pages if you do not also reduce the font size (which is not recommended!). Amazon KDP supports all those formats, but if you decide to have the PDF printed by your local printer, first check which formats your printers supports, otherwise you might have to do some redesigning.

\usepackage[paperwidth=13.34cm, paperheight=20.32cm, inner=0.80in, outer=0.3in, top=0.7in, bottom=0.5in]{geometry} % 5.25’’ x 8’’

Looking at the \usepackage[…]{geometry} command itself, you see the self-explanatory paperwidth and paperheight parameters, as well as four parameters to determine the space between the margins of the book and your text. Instead of parameters that determine left and right margin, you see the parameters inner and outer. Given the way books are bound, the inner margin needs to be significantly larger to account for the joint of the book. If the inner margin were as small as the outer margin, the reader would have difficulties reading the book. In addition, printers are not 100% accurate, so you need to keep some safe space to account for printing errors.

The parameters as defined in the file work nicely for my books. Feel free to experiment with different settings, but make sure you keep them within the range the printing company (be it Amazon or another provider) has defined.

Did you know?

Why choose 5 x 8? Ratios like 5 x 8 are commonly found throughout nature. We find them appealing because our own perception is “calibrated” to find objects displaying this particular ratio. In nature, the fundamental problem for plants is to get as much sunlight as possible. If the leaves are arranged according to a regular pattern, such as “Leaf / quarter-turn / leaf / quarter-turn, …” the leaves will overshadow one another. The challenge is to find an angle of rotation which can be continuously repeated so that no two leaves grow directly above one another (see Figure 6.1). Nature’s solution is using a Fibonacci number sequence (1, 1, 2, 3, 5, 8, 13, 21, …) to calculate the “golden ratio” (5/3, 8/5, 13/8, 21/13, …). -→ Read more in Philosophy for Heroes: Knowledge 

Figure 6.1:Optimal leaf arrangement


If you want to adapt the typography, lib/fonts.tex is the place to look. It consists of:

  • little tweaks for footnotes,
  • line height for lists,
  • space between paragraphs and paragraph indentation,
  • font sizes for captions and the index,
  • font of URLs,
  • background color and font size of listings,
  • typographical tweaks (microtypelmodern),
  • the selection of the font (libertine), and
  • a command that inserts blank pages.

The tweaks are universally recommended, although feel free to select a different font instead of libertine. As the typography is under the control of the specific device when reading the e-book, this applies to only the printable PDF, not the HTML (and thus e-book) output.

The “\sloppy” command is optional; it improves readability by reducing the amount of hyphenation at the cost of possibly more lines of text and more space between the words.

  Chapter Design

The file lib/chapterbox.tex, the chapter box design for the print version, is defined. It replaces the chapter design with a full page with three boxes and the chapter title in huge letters. For the front and back matter, we want the original basic setting with a simple headline with the chapter title and a horizontal line. This can be done by including the file lib/chapterreset.tex before the front matter and before the back matter.

For ease of use, you can use the command

\begin{chapterpage}{Chapter Title}{Chapter Label} …\end{chapterpage}

which is loaded from lib/chapterpage.tex. It sets up the style of the chapter page, as well as the following blank page.

  Header and Footer

In lib/headerfooter.tex, you can edit the style and content of the header and footer. The command


puts the chapter or section title to the inside and the page numbers to the outside of a page. Whether left or right is “inside” depends on whether it is an odd or even page. E-books work on single pages and they have no header, so this command does not affect the style of the e-book output.

The next command, \automark[section]{chapter}, lets the title in the header alternate between the chapter title and section title. If you do not want the section to show up in the header, replace “chapter” with “section.” The third command redefines \headfont that causes the heading to be in small capitals and italics. Finally, the naming of the chapter is redefined, setting it to “Chapter X name of the chapter” without adding a dot after the chapter number.

  TikZ Initialization

TikZ   TikZ is a vector-based drawing language with which you can draw diagrams, charts, tables, fractals, etc.  in high resolution and minimal space.

In lib/inittikz.tex, the TikZ graphics system is loaded. Creating graphics in TikZ goes beyond the scope of this book, but we can help to get you started (see Chapter 3.8). For now we will look only at the initialization.

After loading the basic TikZ packages (and float to add support to force LaTeX to put figures at a certain place), the style of various graphical elements are set up. For example, the text in the nodes of a diagram should have a small font, thick borders, and should be placed a certain distance from other nodes.

By default, tex4ht exports TikZ graphics as vector graphic files (SVG files) and then loads them in the HTML file. Most modern browsers can show vector graphics, but the current e-book converters cannot. They work only with normal images, hence we need to change the behavior of tex4ht.

This is achieved by the code block at the end of the file. It causes all TikZ graphics to be exported into a cache folder, and then to be loaded again from there—as opposed to directly embedded into the PDF as vector graphics.

Long story short, we have to override the tikzpicture command to produce an external PNG file and load that in the HTML file. The PNG files are stored in the tikz-cache/ folder and their resolution can be adapted by changing the density parameter value of the convert command.

Let us look at the details:

  • -extent 1245 This extends the transparent part of the graphic to 1245 pixels. This means all converted TikZ vector graphics will have a width of 1245 pixels.
  • -gravity center If the image is smaller than 1245 pixels, this centers the graphic in the middle of the extended file.
  • -quality 100 Sets maximum compression for TikZ graphics. PNG files are lossless, this increases compile time a little bit, in favor of smaller images.
  • -density 300 Sets the output to 300 dots per inch. This affects the effective size in pixels of the generated graphic.

  Table of Contents

Turning to the next file, lib/tableofcontents.tex, we now arrive at more intricate programming. The first thing you see is that \ifx \HCode \undefined is used instead of \ifxetex. This is because we will be using \HCode to directly insert HTML code into the output. And if HCode is not defined, we will use the normal LaTeX output. But if it is defined, and if our goal is to create HTML files for Amazon, we need to add the ¡nav¿ commands to tell Amazon that what follows now is the table of contents.

For the PDF output, in the case that \HCode is undefined, the command \KOMAoptions{open=…} changes on which side (left or right) the new chapter begins. The template is configured to start chapters on the right side by default (by using the documentclass scrbook—we will discuss this later). For the table of contents, I have decided to let it start on the left (even) page so that the reader can see the full contents of the book in one view. With the following command \KOMAoptions{open=right}, the original setting is restored. Finally, the page needs to be cleared and reset with an empty page style in order to hide the header—we do not want any page numbers in the table of contents section itself.


After finishing my first book, Philosophy for Heroes: Knowledge , I found that it needed additional layers of information to accommodate different types of readers. After considering various options, I decided to add summary (idea) boxes at the end of each section, additional examples, biographies, questions for the reader, and boxes that provide a preview of future books in a series.

Building these boxes is the task of lib/boxes.tex. This file contains a number of graphical elements you can add throughout your book and adapt it to your needs:

\begin{lstlisting}\end{lstlisting} In this environment, everything will be output as you wrote it. This is useful to print out code (like this paragraph) without having to replace all the slashes and braces. The \lstset command determines the formatting of the output, such as break lines at the end of the page, light gray background, indentation, and small font size.

\begin{problem}\end{problem} Creates a box with a question mark icon and the text “Question” on top of it. Use it at the beginning of a section to ask the reader a question that is answered in the following text.

\begin{idea}\end{idea} Creates a box with a light bulb icon and the text “Idea” on top of it. Use it to summarize the previous section and answer the question in the question box.


\begin{example}\end{example} Creates a box with a book and test tube icon and the text “Example” on top of it. Use it for examples that deepen the understanding of the topic in question, but also could be safely skipped.

Biography —Name

\begin{biography}{Name}\end{biography} Creates a box with a book and an identity card as an icon and the text “Biography” on top of it. Some readers want to know more about the people you are discussing in your book, while others want to skip that part. Creating a biography box will accommodate both types of readers. Note the additional parameter (the name of the person), use it like this: \begin{biography}{Alan Watts} Alan Watts was born in …\end{biography}.

Did you know?

\begin{preview}{bibliography id} …\end{preview} Creates a box with an opened book as an icon and the text “Did you know?” on top of it. When referencing your previous books (or giving a preview of your future books), you can use these boxes as an additional advertisement space. It gives the reader an interesting bit to read and might make him or her curious enough to buy or pre-order your next book. Notice the additional parameter (the name of the person), use it like this: \begin{preview}{betterbookswithlatex} In my previous book …\end{preview}. -→ Read more in Better Books with LaTeX

Definition   \begin{definition}{Term}\end{definition} Creates an indented block of text with a black bar to the left (for the PDF output) and the given parameter (the name of the term) in bold and small capitals. This can be used for glossary items to precisely define a concept you have talked about in your text.

Additionally, in lib/quotation.tex, we add support for quotations:

\begin{quotation} …\end{quotation} Creates an intended block of text with a quotation mark graphic in front of it. It signals that there is a quotation from another author. You can use this throughout your book, but I would recommend putting it at the beginning of a section to set the theme or to bring up a certain question.

Finally, we need to display multiple columns in the glossary with lib/multicolbalance.tex.

\begin{multicols}{number of columns}\end{multicols} Splits the text into a number of columns. This is the typical format of the glossary at the end of the book. Books with larger formats might use these throughout the book if necessary. The contents of the columns are balanced (as opposed to filling first the left column and then the right). For readability, the ideal number of columns is two.

  Core Files

Likewise, we already filled the folders mainbackfrontbiographiesexamplesideasquestionsglossary, and images in Chapter 2. We will discuss the remaining files for the HTML conversion in the cssand htlatex folder, as well as the latexmkrc and pgfsys-tex4ht.def files in Chapter 7. Let us now take a look at the core files of a LaTeX project in the root directory. There you can find the language-specific entry files (english.texgerman.tex), and the main project file that binds everything together and provides the structure of the book (main.tex).

As pointed out above in Chapter 6.1.2, in Overleaf , you can select one of the language-specific entry files (english.texgerman.tex) as the main entry file. This way, you can set the language of your project. The parameters american or ngerman of the \usepackage{babel} command reflect this choice. Other than that, the following settings are configured:

  • \documentclass[ …]{scrbook} This sets the document class of your project to a book (two pages and accommodating for the binding). The standard document class is book, using scrbook instead loads a number of additional commands (the KOMA scripts) which we will be using throughout the template. For a detailed documentation of the KOMA script, check out In the template, the pagesize is set to auto, and the bibliography is set to totocnumbered so that it shows up in the table of contents.
  • \title{Title} This sets the title of your LaTeX project. The title will not show up in the final document but is the name of the project listed in Overleaf .
  • \hyphenation{…} Here, you can enter custom hyphenations for fine-tuning. The packages xspace and hyphenat are required for it to work. Not every word is known to LaTeX, and the rules differ between, for example, British and American English. With the hyphenation command, you can enter the hyphenation for special cases yourself. For example, in the Oxford dictionary, “everywhere” is hyphenated as “ev-ery-where” but it might look odd in your text, so you can add \hyphenation{every-where} to tell LaTeX to hyphenate only in the middle. For additional words, simply add them into the bracket: \hyphenation{every-where ti-ger la-tex kit-ten}. You do not need to add a comma or semicolon to separate additional words, just put a space before each new word.

Once the language is set up, the entry file loads lib/packages.tex and then goes into the main file main.tex which is split into five parts:

  • Preamble. For the PDF output, the index is initialized. e-books do not have indexes as they do not have fixed page numbers. Then, the document is started. Everything between \begin{document} and \end{document} is written to the output.
  • Front matter. Front matter pages are numbered with roman numerals (i, ii, iii, iv, …) to set it apart from the main matter. Also, the first few chapters in this part of the book use a basic chapter title formatting (no fancy box). We start with the half title page showing the title, and the title page with the book cover image in case we compile it as a PDF. Then come the publisher, dedication, epigraph, and table of contents page. For the PDF version, we activate the chapterbox formatting to show fancy full-page chapter titles. Next, we show the foreword, and the preface by the author.
  • Main matter. For the main matter, we switch back to a numeric page numbering and insert all the chapter and section files. Here, the bulk of your writing is inserted. This is also the place where you can move around or remove individual sections. For example, if you do not want a page with book advertisements, simply put the comment symbol (%) in front of \input{back/advertisement} and it will no longer appear in the output.
  • Back matter. In the back matter, we show the reader how to proceed from here by advertising our other books and recommending additional books written by other authors to get into the topic more deeply. Next, we insert the author’s biography, as well as the story of how the book was created, giving the interested reader a look behind the curtain. We switch back to the basic chapter design and provide the reader with summaries of the boxes we used (question, idea, and glossary items), as well as a list of sources for the quotations (which we omitted in the text for better readability). Finally, the full bibliography is added in case a reader wants to read in more depth about a certain issue.
  • Appendix. The appendix provides the reader with the index (for the PDF output), a reminder to write a short review online, and farewell words.

Again, you are free to move sections around as you see fit or even disable individual parts by commenting them out (adding a percentage % sign in front of the line). However you decide to design your book, think about what the reader would expect in a certain location of the book. While especially the front and back matter are more or less superfluous parts of a book, they also tell a story and give the reader a context to better understand what you have written in the main part of the book.

This concludes the discussion of the template. In the next sections, we proceed to discuss how to publish the book to specific platforms and polish both the e-book and the print version for release, especially when it comes to graphics.

 LaTeX Help

While we have tested the template together with this book several times, it is likely that you will encounter an issue not discussed here. Creating a document in LaTeX is more complex than in Word, but even in Word there are issues you might run into where the solution is not immediately clear.

If you encounter any error or have a question about LaTeX in the template, please do not hesitate to contact us. The question and the answer might be added to an FAQ for other readers to solve their problems. We offer free support if you provide us with a link to your Overleaf project. For major changes or when more in-depth changes are necessary, one of our LaTeX developers can help you out at an affordable rate. But most issues can probably be solved immediately and for free (“You forgot to close the parentheses,” “You need to load package X,” “Your graphic file is corrupt,” etc.). Simply contact us at and we will see what we can do!

For general LaTeX questions, you can also check out the community at If you post a brief (but working) example of what you are working on, the community can usually provide high-quality advice.