Blog

Turn Your Manuscript into a LaTeX based book

Fri Jan 21 2022 00:00:00 GMT+0000 (Coordinated Universal Time)

A simple way of writing books in LaTeX is using Overleaf and our template. In previous articles, we have walked through the whole “build chain” of creating documents. In this article, we go through each file of the template and give you a “to do” list of items you can work on one by one—from the title to the appendix.

*This is an excerpt from Better Books with LaTeX, the Agile Way**.**‍

Previously, we have covered themain,front, and thebackchapter folders. 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 can be found and allow you to make changes.

Template Library Files

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

Packages File

A packages file is simply a LaTeX file linking to a number of other LaTeX files or containing additional functionality not provided in the default LaTeX configuration. To import a package in LaTeX, you simply use the**\usepackagecommand before the\begin{document}**command. In the template, thelib/packages.texfile loads all the other files in thelibdirectory and also loads some additional packages, depending on the output format.

The first two commands load thenagpackage 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 quickly.

Theifxetexpackage loads a small script that we can use to check whether the target platform is a printed PDF (withXeLaTeX) or an HTML file (withpdfLaTeX). It follows the basic format of:

\ifxetex{}(executed ifXeLaTeXis used)\else{}(executed ifpdfLaTeXis used)\fi{}

Think of**\ifxetex{}**as the main junction between the e-book (the HTML file output usingpdfLaTeX) and the print book (the PDF file output usingXeLaTeX).

Next are several packages and configurations specific to either of those platforms. Theadjustboxpackages adjust figures to fit onto a page—a feature needed only for the printed PDF as e-book readers automatically adjust graphics depending on the screen resolution. Thepsvectorianpackage allows us to add curly horizontal lines at the end of sections and chapters—a feature not supported by e-books.

TeX4ht⋅TeX4htis a tool to translate LaTeX code into an HTML document.

The next command,\hrule, is not supported byTeX4ht, so we create a specific command,\myrule, and translate it into an HTML**


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 thelibdirectory are loaded, so we need only to includelib/packages.texto load the entire configuration. On the following pages, I will discuss each package.

Language Selector

In an Overleaf project that is based on the template, you can select the language by changing the parameter of thebabelpackage inoutput.tex. In the file, either the command**\babelDEor\babelENgets activated by the command\usepackage[ngerman]{babel}or\usepackage[american]{babel}, respectively. The command sets\languagenameeither to “ngerman” or “american.” Inlib/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, for example, Spanish, replace “american” with “spanish” inoutput.tex(\usepackage[spanish]{babel}). Next, add the following commands inlib/languageselector.texand you are ready to use**\babelES**as a command in your text.

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

Bibliography

Inlib/bibliography.tex, the bibliography feature is added to the document and (due to compatibility issues) either loadsbiblatexornatbibdepending on whether you useXeLaTeXorpdfLaTeX. It also loads the actual bibliography file from thebibliographydirectory, depending on the language you have selected previously. The parameters of loadingbiblatexdetermine whether cited titles should be added to the index automatically (“indexing=cite”) and 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 settingauthortitlein 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 thenamereflibrary. 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. Any changes to 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} Chapter ‘‘My First Chapter’’ discussed 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{How I Bought My Car}\label{c1_myfirstchapter:sec} Yesterday, I bought a car. \chapter{My Second Chapter}\label{c2_mysecondchapter:sec} Chapter~\nameref{c1_mychapter:sec} discussed buying a car.

Book Format

Next islib/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 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.

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

**Did you know?**Why choose 5 x 8? Ratios like 5 x 8 are found throughout nature. We find them appealing because our perception is “calibrated” to find objects displaying this particular ratio. Why? 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 17.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 [Lode, 2016]**Figure 17.1:**Optimal leaf arrangement

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 local printer supports, otherwise you might have to do some redesigning.

Looking at the**\usepackage[…]{geometry}**command itself, you see the self-explanatorypaperwidthandpaperheightparameters, 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 margins, you see the parametersinnerandouter. Given the way paperback books are bound, the inner margin needs to be significantly larger, otherwise the reader would have difficulties reading the book. Also, 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.

Fonts

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

  • Little tweaks for footnotes,
  • Line height for listings,
  • 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 (microtype,lmodern),
  • 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 oflibertine. As the typography is under the control of the specific device when reading an e-book, this applies to only the printable PDF, not the HTML (and thus e-book) output.

The**\sloppycommand is optional; it reduces the readability of some lines, but it ensures that no lines go beyond the left or right border (something that makes printing the book impossible). For further optimization, you could (after having finished the book using the sloppy command) replace it with the\fussy**and manually fix any issues with text going beyond the border. Both commands change parameters of how to stretch spaces between words and how to handle hyphenation.

Chapter Design

For ease of use, you can use the command:

\begin{chapterpage}{title}{label}…\end{chapterpage}

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

The actual design of the chapter page for the print version is changed in the filelib/chapterbox.tex. It replaces the standard chapter design and uses a full page with a border and the chapter title in large letters.

To reset the chapter page design to the default settings (for example, for all back matter chapters) with a simple headline with the chapter title and a horizontal line, use either**\input{lib/chapterfont.tex}or\chapterinstead of\begin{chapterpage}**.

Header and Footer

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

\ihead[\headmark]{\headmark}\ohead{\pagemark}

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. If you are working on an e-book, you can safely ignore this command because pages of an e-book have no header, footer, or page number.

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**and causes the heading to be in small capitals and italics. Finally, the naming of the chapter is redefined, setting it to “Chapter Xname of the chapter” without adding a period after the chapter number.

TikZ Initialization

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

Inlib/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 this article).*For now, we will look only at the initialization.

After loading the basic TikZ packages (including thefloatpackage, which allows you to put a figure at a specific place in the text instead of having the LaTeX compiler decide), the style of various graphical elements is 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,TeX4htexports 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 regular images, hence we need to change the behavior ofTeX4ht. 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 thetikzpicturecommand to produce an external PNG file and load that in the HTML file. The PNG files are stored in thetikz-cache/folder. Their resolution can be adapted by changing thedensityparameter value of theconvertcommand.

Let us look at the details:

  • -extent 1245This extends the transparent part of the graphic to 1,245 pixels. This means all converted TikZ vector graphics will have a width of 1,245 pixels.
  • -gravity centerIf the image is smaller than 1,245 pixels, this centers the graphic in the middle of the extended file.
  • -quality 100Sets maximum compression for TikZ graphics. This reduces the file size, at the cost of an increased compile time.
  • -density 300Sets 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. For the table of contents in the e-book, we need to insert code directly into the HTML output file. So, we check whether the current compiler supports**\HCode**(onlyTeX4htsupports that), and insert**

Get in Touch

We speak English (native), German (native), and French. Let's discuss your project!