Categories
LaTeX

Adding TeX4ht to Your LaTeX Book Project

This is an excerpt from Better Books with LaTeX the Agile Way. You can get a copy here.

TeX4ht Configuration

Here, 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 are already using the configuration set up by the template, you can safely ignore this chapter.

To convert LaTeX to HTML, we need an additional compiler, TeX4ht, which works only with pdfLaTeX. If you are using XeLaTeX (or other LaTeX compilers) for your project, you might run into some problems when switching to pdfLaTeX. You can stay compatible with both compilers by using the conditional \ifxetex statement we have discussed in another article and the book.

On the Overleaf platform, no separate installation for TeX4ht is needed. All you need to do is include it by adding a file named latexmkrc in the main directory (and thus overriding the latexmkrc provided by Overleaf by default) of your project and adding a configuration file.

Figure 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 and configure compilers for a different output format (like using TeX4ht to generate HTML output in addition to generating a 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 https://www.overleaf.com/help/216-how-does-overleaf-compile-my-project):

 
 
$pdflatex = "rm tikz-cache/*.pdf; pdflatex -shell-escape -synctex=1 %O %S; htlatex %S \"htlatex/htlatex.cfg,MyFonts,NoFonts\" \"\" \"\" -shell-escape > output.txt"; 
END {system(’zip -r allfiles.zip . -x *.cache*’);}  

This creates a hook in the compilation chain of LaTeX (LaTeX calls $pdflatex at the end of the compilation). All this does is clear the cache, call pdflatex before calling htlatex, giving you a PDF output (and compilation of TikZ images) in addition to the HTML output. It also writes the output of the compilation of htlatex to a new file called output.txt to be used for debugging. At the end, it zips all the files of your project into the allfiles.zip for later download. You can download the output files (clicking on the Logs and output files icon at the top of the right window, scrolling all the way down to Other logs & files, and selecting the previously created allfiles.zip).

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. This is discussed in another article and the book.

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:

 
 
\Preamble{xhtml} 
 
\Configure{VERSION}{} 
\Configure{DOCTYPE}{\HCode{<!DOCTYPE html>\Hnewline}} 
\Configure{HTML}{\HCode{<html>\Hnewline}}{\HCode{\Hnewline</html>}} 
\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{emph}{\ifvmode\ShowPar\fi\HCode{<em>}}{\HCode{</em>}} 
\Configure{textbf}{\ifvmode\ShowPar\fi\HCode{<strong>}}{\HCode{</strong>}} 
\Configure{textit}{\ifvmode\ShowPar\fi\HCode{<em>}}{\HCode{</em>}} 
\Configure{texttt}{\ifvmode\ShowPar\fi\HCode{<code>}}{\HCode{</code>}} 
\Configure{textsc}{\ifvmode\ShowPar\fi\HCode{<span class="sc">}}{\HCode{</span>}} 
 
% Translate verbatim and lstlisting blocks into <pre> elements 
\ConfigureEnv{verbatim}{\HCode{<pre>}}{\HCode{</pre>}}{}{} 
\ConfigureEnv{lstlisting}{\HCode{<pre>}}{\HCode{</pre>}}{}{} 
\ConfigureEnv{minipage}{\ifvmode\IgnorePar\fi\HCode{<div class="minipage">}}{\ifvmode\IgnorePar\fi\HCode{</div>\Hnewline}}{}{}% 
 
% Do not set ‘indent‘/‘noindent‘ classes on paragraphs 
\Configure{HtmlPar} 
{\EndP\Tg<p>} 
{\EndP\Tg<p>} 
{\HCode{</p>\Hnewline}} 
{\HCode{</p>\Hnewline}} 
\begin{document} 
\EndPreamble  

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 (\emph\textbf\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 \HCode command directly inserts HTML commands in the output file and can also be used in the regular LaTeX files. For example, you can use

 
 
\HCode{<hr style="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 and 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. Add support for small capitals:

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

5. Print description list elements in bold:

 
 
dt.description { font-weight: bold; }  

This is an excerpt from Better Books with LaTeX the Agile Way. You can get a copy here.

Categories
LaTeX Publishing

Polishing for E-book Release

This is an excerpt from Better Books with LaTeX the Agile Way. You can get a copy here.

Polishing for an e-book release is significantly easier than for a PDF print release. This is because the reading software or device on which your book is displayed for the reader reformats your book to fit correctly on a particular screen. Also, printed books have individual pages, while e-books do not. Your e-book’s contents are handled like a one-page website where you simply scroll from top to bottom. In some cases (for example, new chapters, title pages, or publisher pages), it makes sense to enforce a page break even in an e-book with \nextpage.

If you plan to release your book as an e-book as well as releasing a print version (which I recommend), you should first finish and release the e-book version and then work on polishing the print version. This is because there are additional steps required for the print version (like cleaning up empty pages and creating the index).

Preparing Images for E-books

Text can easily fit on any screen because it is very flexible, but images are not. They are not reinterpreted and adapted to a specific device; rather they are simply scaled to fit into the reader’s screen. Text does not lose quality when being adapted to a particular screen resolution, while image quality might suffer significantly.

For e-books, lossy JPG files are preferred because, on Amazon, distribution costs per book are not by page, but by the file size of the e-book for each download. Except for the cover graphic (which is uploaded separately), you should use low-resolution images (300 dpi) throughout your book as the device on which the image will be shown will most likely have a low resolution, too.

One major difference between e-books and printed books is that you can get color for free, at least on some devices. On other devices, all graphics are converted to grayscale versions. Here, it is up to you whether you want to provide an extra service for owners of more modern devices (or who read the book on a smartphone) or have print and electronic versions of your book identical when it comes to graphics. If you decide on grayscale images, you will save around a third of the file size. For example, this photo of the Milky Way has a size of 328 kb in color, but only 250 kb in grayscale (see Figure 19.1).

Figure 19.1: An image of the Milky Way (image source: wikipedia)

Another difference is scaling. For the print version, you can use \adjustbox{} to fit an image into the dimensions of a page. For the e-book version, images are scaled automatically to the width of the screen. While this saves you the work of scaling it yourself, you might end up with images larger than intended (and thus having a lower resolution) in those cases where you have scaled down the picture in the PDF version.

For all TikZ graphics, this is configured in the lib/inittikz.tex file (see Chapter 17.1.8): all TikZ graphics are automatically converted to PNG files with a fixed width (1,245 pixels by default). Instead of being scaled up, the transparent background of smaller graphics is simply extended.

For smaller, non-TikZ graphics that you include from external sources (e.g., JPG images), you should make sure that there is sufficient space left and right of the image. This ensures that they are not distorted during the e-book conversion process. Larger images for which you are already using the full width of the page in the print version do not have to be edited as they will be scaled down automatically. Alternatively, make it a rule for yourself to not use \adjustbox{} in the print version and instead do all the scaling manually by editing the image externally in a graphics editor. The benefit of this approach is that you do not need a separate e-book version of your images.

If you are using images with fonts, lines, or diagrams in them, make sure to be consistent and use the same font sizes and line thickness throughout your book. This can be a significant challenge if you do not have access to the original image files. For that reason, for any new images you want to add, I strongly recommend using vector graphics (or TikZ graphics) as the image source.

This is an excerpt from Better Books with LaTeX the Agile Way. You can get a copy here.

Categories
Editing LaTeX Publishing

Polishing a Book for Print

This is an excerpt from Better Books with LaTeX the Agile Way. You can get a copy here.

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 not something 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 writing, 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. 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, forcing page breaks and having sections starting on the right side can lead to a number of blank pages.

Let us examine several items to keep in mind:

  • 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 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 improve readability by splitting it into smaller parts.
  • Shortening sentences. If your paragraph spans to the next page due to just a few words, edit the paragraph.
  • 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, eliminating unused white space.
  • Shrinking images. Besides simply rearranging images, you can also limit their size by either changing the limits of the \adjustbox{} command or by making the image itself smaller. Be advised that using \adjustbox{} should be the last resort. While scaling photographic images is no problem, any image containing fonts, lines, tables, etc. will end up not looking good. If you want to scale such vector graphics down, the better option is to make changes to the actual graphic, for example by reducing the distance between elements in a diagram, making the overall image more compact while keeping the original font and line sizes.
  • 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 blank space as discussed above. You can do that by simply adding \newpage (or \blankpage if you want to finish the current page and add a blank page). As mentioned in Chapter 14.1, this does not affect the e-book version of your book.

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 with respect to images is if he or she does not need to browse back and forth to connect what you write about a particular image and the image itself.

If you encounter any “orphaned 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 (https://get.adobe.com/reader/), 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 look at the pages exactly as they would appear in the printed book, with the even page numbers on the left and the odd page numbers on the right. The formal terms for these are “verso” for the left-side page of a book and “recto” for the right-side page. By book publishing convention, the first page of a book (and in the template, of each chapter) is a recto page.

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. Use these file formats whenever possible. TikZ graphics produce vector graphics, and stock image sites like shutterstock.com offer many files both as regular image files and vector graphics. Both EPS and PDF files will work, although PDF files are the preferred format because they do not need to be converted but can be embedded by LaTeX directly into the final PDF.
  • 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 is better to use lossless PNG images if you have them available.

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 14.9). For lossless and lossy images, choose a resolution of 600 dots per inch (dpi), as printers usually use this resolution for black on white printing.

resolutionuseuse it with
Lossy JPG300-600 dpie-booksphotos
Lossless PNG600 dpiPDFphotos, diagrams
Vector graphicsn/abothgraphs, diagrams
Figure 18.1:Comparison of graphic formats and their application.

Gimp ⋅  Gimp is a free graphics editor (https://www.gimp.org) 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., 1,245) 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 1,245-pixel-wide image with 300 dpi will appear smaller than a 1,245-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.25 in – 0.8 in – 0.3 in = 4.15 in. With a desired resolution of 600 dots per inch, you need an image with a width of 4.15 in * 600 = 2,490 pixels.

Lightshot ⋅  Lightshot is a free screenshot utility (see https://app.prntscr.com) 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 120 dpi. 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.990 dpi to 300 dpi does the trick.

This is an excerpt from Better Books with LaTeX the Agile Way. You can get a copy here.

Categories
Editing LaTeX Publishing

The LaTeX Book Template

This is an excerpt from Better Books with LaTeX the Agile Way. You can get a copy here.

In a previous article (and the book), we we have covered the mainfront, and the back chapter folders of the LaTeX Template. 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 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

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 \usepackage command before the \begin{document} command. In the template, the lib/packages.tex file loads all the other files in the lib directory and also loads some 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 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 several packages and configurations specific to either of those platforms. The adjustbox packages 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. The psvectorian package allows us to add curly horizontal lines at the end of sections and chapters—a feature not supported by e-books.

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

The next command, \hrule, is not supported by TeX4ht, so we create a specific command, \myrule, and translate it into an 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 need only to include lib/packages.tex to 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 the babel package in output.tex. In the file, either the command \babelDE or \babelEN gets 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, for example, Spanish, replace “american” with “spanish” in output.tex (\usepackage[spanish]{babel}). 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} 
\babelES{\renewcommand{\contentsname}{Contenido}}  

Bibliography

In lib/bibliography.tex, the bibliography feature is added to the document and (due to compatibility issues) either loads biblatex or natbib depending on whether you use XeLaTeX or pdfLaTeX. It also loads the actual bibliography file from the bibliography directory, depending on the language you have selected previously (see Chapter 17.1.2). The parameters of loading biblatex determine 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 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. 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 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 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 [Lode2016]


PIC
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-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 margins, you see the parameters inner and outer. 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.tex is 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 (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 an e-book, this applies to only the printable PDF, not the HTML (and thus e-book) output.

The \sloppy command 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 from lib/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 file lib/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 \chapter instead of \begin{chapterpage}.

Header and Footer

In lib/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 X name of the chapter” without adding a period 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 using 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 14.9). For now, we will look only at the initialization.

After loading the basic TikZ packages (including the float package, 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, 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 regular 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. 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 1,245 pixels. This means all converted TikZ vector graphics will have a width of 1,245 pixels.
  • -gravity center If the image is smaller than 1,245 pixels, this centers the graphic in the middle of the extended file.
  • -quality 100 Sets maximum compression for TikZ graphics. This reduces the file size, at the cost of an increased compile time.
  • -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. 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 (only TeX4ht supports that), and insert <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. This is accomplished by the command \thispagestyle{empty}\pagestyle{empty}\clearpage.

Boxes

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 graphical elements you can add throughout your book and adapt to your needs. Please note that the box icons are not included in the template; upload them on your own and uncomment the relevant lines in lib/boxes.tex.

\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} For the print book, it creates a box with a question mark icon and the text “Question” at the top of the box. Use it at the beginning of a section to ask the reader a question that is answered in the text.

\begin{idea}…\end{idea} For the print book, it creates a box with a lightbulb icon and the text “Idea.” Use it to summarize the previous section and answer the question in the question box.


Example

\begin{example}\end{example} Creates a box with a book and test tube icon and the text “Example.” Use it for examples that deepen the understanding of the topic in question, but 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.” 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?” at the top. When referencing your previous books (or giving a preview of your future books), you can use these boxes as additional promotional 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 book), use it like this: \begin{preview}{BBWLtAW} In my previous book …\end{preview}. → Read more in Better Books with LaTeX the Agile Way [Lode2019]


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 written about in your text.

\begin{quotation} …\end{quotation} Creates an intended block of text with a quotation mark graphic in front of it. It signals that this 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 particular 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 several 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

We already filled the folders main/back/front/biographies/examples/ideas/questions/glossary/, and images/ in Chapter 13. We will discuss the remaining files for the HTML conversion in the css/ and htlatex/ folder, as well as the latexmkrc and pgfsys-tex4ht.def files in the appendix in Chapter 24. Let us now take a look at the core files of a LaTeX project in the root directory. There you can find the entry file that initializes the language settings (output.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 17.1.2, in Overleaf, you can change the language of your project in output.tex. 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, introducing odd and even pages with extra space in the middle for the binding. The standard document class is book, using scrbook instead loads several additional commands (the KOMA scripts) which we will be using throughout the template. For detailed documentation of the KOMA script, check out https://www.ctan.org/pkg/koma-script. 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. This 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. The numbering begins on the title page (not the cover itself) with the command \frontmatter. The template is also set up to use only basic chapter title formatting (no fancy box) for all the chapters in the front matter. To hide page numbering on a certain page (for example, the title page), add \thispagestyle{empty} at the beginning of the page.We start with the half title page showing the title, and the title page with the book cover image when compiling 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 numeric page numbering and insert all the chapter and section files. This is where the bulk of your writing will be added. 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. Remember to use a separate tex file for each individual chapter. If you copied your entire book into the main.tex file, organization would become difficult.
  • 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. 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.
  • 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). As you organize your book, think about what the reader would expect in a particular 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, and why.

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

While we have tested the template together with this book several times, you will likely encounter an issue not discussed here. Creating a document in LaTeX is more complicated than in Word. Remember: If you encounter any error or have a question about LaTeX in the template, please do not hesitate to contact us at [email protected] and we will see what we can do!

This is an excerpt from Better Books with LaTeX the Agile Way. You can get a copy here.

Categories
Editing LaTeX Publishing

Index Creation in LaTeX

This is an excerpt from Better Books with LaTeX the Agile Way. You can get a copy here.

As opposed to their electronic counterparts, printed books do not have a search functionality to find specific words in the text. Instead, they have an index at the end as a service for the reader to quickly find certain parts of the book that he or she wants to read. If you are planning to publish only an e-book version of your book, you could skip this section—e-books do not have indexes because they do not have fixed page numbers: they are formatted differently on different devices. Keep in mind, though, that you might want to create a paperback edition at a later date and that your knowledge about your book is still fresh now. Even without a paperback edition, working on an index will help you to find possible keywords you could use for marketing, and it is a useful method of reviewing your book’s content paragraph by paragraph.

Unfortunately, there is no easy way to generate an index automatically—at least not in the quality a human can. Why is that?

Beyond merely listing all the concepts in a book, a good index is like an intelligent filter. The person creating the index has to think about what a reader might search for and list that word, even though it might never literally appear in the book. Likewise, if a concept consists of multiple words, it might be good to include both variations, for example, “language → mathematics” and “mathematics → language” to refer to the language of mathematics and mathematics as a language.

But how can LaTeX help in this regard? In traditional bookmaking, creating the index of a book is a separate process after the actual book is finished. You can imagine it basically as having the printed book in front of you, then going through page by page, noting which concepts appear on a particular page. This approach gets problematic if you want to make changes to the book that affect the page numbers: you would have to redo the entire index each time.

Indexing in Word

In Word, you can select the word or words you would like to use as an index entry and click on Mark Entry (on the References tab, in the Index group). A dialog shows up (see Figure 16.1) where you can configure the index entry (search for “Create and update an index” to find Microsoft Office help on this topic). Once done, Word switches into a hybrid mode that shows things like line breaks or index entries which are usually hidden (you can activate/deactivate the mode yourself by clicking on the ¶ button). If you want to edit an existing index entry, you have to edit the generated code. For example, the code for a subentry “mathematics” of the index entry “language” looks like this in Word:

 
 
Mathematics{*XE*"language:mathematics"*}  
PIC
Figure 16.1: Marking an entry to add it to the index in Microsoft Word.

Indexing in LaTeX

In LaTeX, insert the index command by adding the \index{…} directly into the text. For example, if you have the sentence “The yellow lab was voted America’s favorite dog again this year,” you could add two entries: “The yellow lab\index{yellow lab} was voted America’s favorite dog\index{favorite dog} again this year.” The page number that shows up in the index will then correspond to the place where you have inserted the index command. If the sentence “The yellow lab was voted America’s favorite dog again this year,” is printed on page 7 of the book, the index will show “yellow lab, 7” and “favorite dog, 7” assuming there is no mid-sentence page break.

The big question is: which words should you index? Let us look at an overall indexing strategy.

My approach in the first phase is to index all the terms that need to be indexed no matter what. Those are:

  • Names of persons. Whenever you mention (or quote) a person, add the index command after his or her name. The format for indexing someone’s name is \index{last name, first name middle name}, for example, \index{Darwin, Charles Robert}.
  • Media titles. Likewise, whenever mentioning a work of art (book, movie, software, etc.), add the index command after its title. If you have the title in your bibliography, \citetitle{bookid} does the job for you and adds the item automatically to the index. The “bookid” stands for the id you have given in the bibliography file. The exception to using \citetitle would be titles that start with an article (a, the) which is usually put at the end (e.g., Last Unicorn, The instead of The Last Unicorn). In those cases (or when you do not reference a book from your bibliography), use \index{title of the [email protected]\textit{title of the work}}. The “@” character is necessary for the indexing engine to recognize the italic font formatting.
  • Concept definitions. When introducing a concept and providing its definition (especially in glossary items), you want the reader to look at a particular passage before any other. When indexing, you can accomplish this by marking those entries in bold by adding “|textbf”: \index{word|textbf}. For example:  
    Science\index{science|textbf} is the formalized process of gaining new knowledge.  

Note that you must not index entries within captions of figures. This will cause problems during compilation. Instead, index the place where the figure is referenced in the text.

Once those basics are implemented, you move into the second phase. Here, you go from paragraph to paragraph and ask yourself each time what concepts are discussed. Add the first occurrence of each concept to the index. This paragraph-by-paragraph approach is the best compromise between accuracy and usability. You save time by adding a particular concept to the index only once per paragraph. The reader sees if a paragraph on a particular page spills over to the next page and will read on. The index page number basically says “start reading here until the paragraph is finished.”

If the same word is indexed in multiple paragraphs, LaTeX will combine them into a single index entry. That is, a single number if all occurrences are on the same page, or a list (or range) of pages where the concept is discussed (e.g., “5-7, 9”, “273-279, 401”, etc.).

To prevent confusing the reader with too many index entries, it is important to not index simply because a particular word is mentioned; the paragraph should explain something about the word or concept in question. Imagine the reader looking up the word in the index, going to the page, and then wanting to read what the word in question is about. For example, take the sentence “A republic is different than a democracy as it sets the constitution as its highest arbiter.” Of course, you would index “republic” in this sentence. But if you also indexed “democracy,” a reader will gain little value from it. From this sentence, the reader does not get any explanation of what democracy is about. If the sentence was instead “A republic is different than a democracy as it puts the constitution, not the people, as its highest arbiter,” the situation would be different. It describes (an aspect of) democracy. Of course, it is not a definition of democracy, so you would not mark it as bold in the index. Alternatively, you can also always use more general concepts in an index. Here, you could use “systems of government” instead of either republic or democracy, especially when you are just comparing different systems of government in that paragraph. Even if you never use the expression “systems of government” in your book, a reader will be satisfied reading the paragraph as it compares systems of government. As the following phases will only remove or combine indexes, it is safe to “overindex” in this second phase. You can even add multiple index entries for individual words. Using the example from above, you could add both “republic” and “systems of government.”

Once you are done with indexing individual words, in phase three, you can take a break and have your editor (or a friend) take the role of a reviewer. Alternatively, take an extended break and revisit your book one month later with a fresh mind. For the review, go one by one through the index, go to the page specified, and ask yourself if the passage really explains the concept. If not, remove the entry from the index.

Phase four then deals with cleaning up this “overindexed” index. Look at the index and see if you can find entries that can be combined. For example, you might find you have the following entries in your index: “Greek alphabet,” “Latin alphabet,” and “Phoenician alphabet.” Here you have to ask yourself if your readers might also search for “alphabet” or already have a specific language in mind. In my book Philosophy for Heroes: Knowledge , I decided for the former and combined the index entries into the category “alphabet” with “Greek,” “Latin,” and “Phoenician” as subcategories. This categorization can be done in LaTeX with the following construct:

 
\index{main category!subcategory}
 
                                                       
                                                         

In our example, use \index{alphabet!Greek}\index{alphabet!Latin}, and \index{alphabet!Phoenician}, respectively. You can also go one level deeper, although that should be the exception. For example, you could categorize “natural numbers in mathematics” as \index{mathematics!number!natural}. In both cases, LaTeX will automatically combine those three entries and arrange them together. With this in mind, I recommend reading a few indexes of the books in your library to learn how the authors combined their concepts. If you want to know more about the theory of knowledge and categorization of language in philosophy, check out Philosophy for Heroes: Knowledge , which explains it in detail.

Next, in phase five, you might want to explain to the reader the case of two different words in the index referring to the same concept. Maybe there is a popular expression for something and (in your field of work) the correct expression for something. In the index, you can point one expression to the other. For example, one application is when citing a person who has different names, maybe a real name and an artist name. Readers might look for either version of the name. For example, the mathematician Leonardo Bonacci is also known as Fibonacci. You might list both names and tell the reader that you are referring to the same person. If you used “Leonardo Bonacci” in your text, you could add an index entry with the following format: \index{one version of the word|see{other version of the word}}. In our case this would be “Leonardo Bonacci was a famous mathematician.\index{Bonacci, Leonardo}\index{Fibonacci|see{Bonacci, Leonardo}}.” Another example and a bit of an inside joke would be recursion: “If a statement relates to itself, it is called recursive.\index{recursion}\index{recursion|see{recursion}}.”

Finally, read through the entire index again to identify double entries, e.g., the same concept listed twice because of a misspelling. These can happen because the LaTeX commands are hidden in any PDF output you might be using for proofreading. That is it!

Here again are the steps of the index creation as a list:

  • Index all the basic terms (titles, people and place names, definitions).
  • Go through the entire text and index all the terms that are explained in a particular passage.
  • Check all index entries by going backward from the index to the text.
  • Combine index entries into groups.
  • Add references from one index entry to another (e.g., for people with several names).
  • Check for spelling errors.

This is an excerpt from Better Books with LaTeX the Agile Way. You can get a copy here.

Categories
LaTeX Publishing

Bibliography and Citations in LaTeX

This is an excerpt from Better Books with LaTeX the Agile Way. You can get a copy here.

Science is a collaborative enterprise spanning the generations. When it allows us to see the far side of some new horizon, we remember those who prepared the way.

Carl Sagan, Cosmos: Blues for a Red Planet

Books build upon other books, just like scientific experiments build on other scientific experiments. Be it out of scientific accuracy, as a service to the interested reader, or out of gratitude, you should include references to your sources. Personally, I love to know the source of an author’s ideas.

In Word, there is no built-in way of managing a bibliography (other than manually writing each entry and referencing it in the text). You can check out plugins like Zotero (https://www.zotero.org).

Zotero ⋅  Zotero is a plugin for Word (see https://www.zotero.org) which integrates into Word and your browser so you can fetch bibliographical information from the web and import it via a menu in Word.

In LaTeX, the support for a bibliography is inbuilt. All entries are saved in the file bibliography/english.bib. The file is structured as a list of entries of the format TYPE{id, title={ title }, author={ author }, year={year of release}, …}. While LaTeX allows special characters like colons to be used in the id field, I recommend using only lowercase characters and numbers. Besides the title and release year, an entry can have a number of different parameters depending on its type. The main types are:

  • @BOOK If the entry references a book, use this type. Additional entries are isbn, and publisher.
  • @ARTICLE Articles published in scientific journals have this type. Additional entries are journalpages, and publisher.
  • @MISC Any other source (for example, websites or movies) falls under this category. Additional entries are url, and note. If you are referencing a website, add a note that contains something like “note = { [online; last accessed March 3rd, 2018] }” as the website’s contents might change. Ideally, keep a local copy of the website for yourself in case it vanishes. Please note that for the url field, include “http://” or “https://” at the front to make it a valid field.

Please note that Amazon prohibits the use of Amazon affiliate links within e-books.

The template is already set up to load the entries of bibliography/english.bib. With the following commands, you have access to all bibliographical entries within this file:

  • \citetitle{id} This command prints out the title specified in the corresponding entry in the bibliography. For example, \citetitle{BBWLtAW} writes the title of this book in italics: Better Books with LaTeX the Agile Way. In addition, it adds the title to the index of the book.
  • \cite{id} This command prints out the reference to the media and creates a link to the bibliography in the back matter.
  • \citep{id} This command is the same as above but puts parentheses around the reference.
  • \footcite{id} This command is the same as above but puts the citation into a footnote.

Concerning the citation itself, many different formats include a combination of year, title, and author. If you want to use a different format, check out the documentation at https://ctan.org/pkg/bibtex and make the corresponding changes in lib/bibliography.tex.

Bibliographical Information

To fill the bibliography with media you cite from, the most straightforward approach is to go to Amazon, search for the book or movie title, and copy the information (author, publisher, ISBN, etc.) manually into a new entry. If you are citing scientific articles, look for a button on a website that says something about exporting or downloading a citation in BibTeX. This way, you can download an already filled-out bibliographical entry and copy and paste it into your bibliography/english.bib library.

As an example, the BibTex entry for this book is:

 
 
@BOOK{ BBWLtAW, 
    author = { Lode, Clemens }, 
    title = { Better Books with LaTeX the Agile Way}, 
    keywords = { }, 
    isbn = { 978-3-945586-48-8  }, 
    publisher = { Clemens Lode Verlag e.K. }, 
    year = { 2019 }, 
    type = { Book }, 
    subjects = { Publishing; Marketing; Project Management } 
}  

This is an excerpt from Better Books with LaTeX the Agile Way. You can get a copy here.

Categories
LaTeX Publishing

LaTeX Basics

This is an excerpt from Better Books with LaTeX the Agile Way. You can get a copy here.

This article will cover the basics of LaTeX so that you can make adjustments to your existing texts, understand the commands in the template, and get a head start for when you want to learn more complex commands on your own.

Basic Formatting

  • Comments. If you want to just add a comment to a file without it being printed, add a % (percentage) sign in front of it. In Overleaf, the text in the affected line will be displayed in a different color. In the template files, you will find several such comments as well as deactivated commands (for example, in lib/bookformat.tex the different options for the book size).
  • Bold formatting. You can make your text bold by either selecting it and pressing CTRL + b (in Overleaf), or by surrounding it with the command \textbf{Your Text}.
  • Italics formatting. You can italicize your text by either selecting it and pressing CTRL + i (in Overleaf), or by surrounding it with the command \textit{Your Text}.
  • Small caps. You can change your text into small capitals by surrounding it with the command \textsc{Your Text}.
  • Em dashes. Em dashes are used to connect two related sentences and can also be used instead of parentheses or commas. There is no space before or after the em dash. Within the template, use the command \emdash{} instead of using the dash you copied over from your text file—this will also take care of issues relating to line breaks.
  • Paragraphs. Paragraphs are handled automatically by leaving an empty line between each paragraph. Adding more than one empty line will not change anything—remember Overleaf is not a “what you see is what you get” editor.
  • Empty line. If you want to force an empty line (recommended only in exceptional cases), you can use ˜\\ (tilde followed by two backslashes). Possible applications are in the front matter; for example, in this book, I have used it for the title and half-title page, as well as the publisher page, and the preface and foreword (for the signature at the bottom).
  • New page. Pages are handled automatically by LaTeX. It tries to be smart in terms of positioning paragraphs and pictures. Sometimes, (ideally, at the very end when polishing the final text), it is necessary to add a page break. For that, simply add a \newpage. If you want to insert a page break in your e-book version, too (for example, after chapters or special pages like the title or publisher page), use \nextpage instead.
  • Quotation marks. In the standard computer character set, there are several types of quotation marks. It is required to change all quotation marks into  (two back ticks at the beginning and two single ticks at the end). Refrain from using ”…” (or “…”) to prevent issues with the LaTeX compilation.
  • Horizontal line. For a horizontal line, simply use \hrule:_____________________________________________
  • Underlined text. It is generally not recommended to use underlined text in books.
  • URLs. For URLs, you need a special monospaced font. Also, for URLs in e-books, you want to make them clickable. Both can be accomplished by putting the URL in the \url environment, for example, \url{https://www.lode.de}https://www.lode.de
  • Special characters. If you need special characters or mathematical formulas, there is a whole body of work on that subject. Check out tug.ctan.org/info/symbols/comprehensive/symbols-a4.pdf for a comprehensive list.

Lists

Itemized list. To create a bullet point list (like the list in this section), use the following construct:

 
 
\begin{itemize} 
  \item Your first item. 
  \item Your second item. 
  \item Your third item. 
\end{itemize}  

The result will look like this:

  • Your first item.
  • Your second item.
  • Your third item.

Numbered list. To create a numbered list, replace itemize with enumerate:

 
 
\begin{enumerate} 
  \item Your first item. 
  \item Your second item. 
  \item Your third item. 
\end{enumerate}  

The result will look like this:1.Your first item.2.Your second item.3.Your third item.

Verbatim Text

Sometimes, you may want to simply use text in a verbatim way (including special characters and LaTeX commands). For this, simply use the lstlisting environment: \begin{lstlisting} …\end{lstlisting}. For example, I put the itemize and enumerate listings above into a lstlisting block. If I did not, LaTeX would have displayed the list as a list, instead of displaying the code.

Chapters and Sections

LaTeX uses a hierarchy of chapters, sections, and subsections. There are also sub-subsections, but for the sake of the reader, it is best to not go that deep. If you come across a situation where it looks like you need it anyway, I recommend thinking over the structure of your book rather than using sub-subsections.

In terms of their use in the code, they are all similar:

  • \chapter{Title}\label{c1_chaptername:cha}
  • \section{Title}\label{c1_sectionname:sec}
  • \subsection{Title}\label{c1_subsectionname:sec}

When using these commands, obviously replace the title, but also the label. For the label, I recommend beginning the label with c, followed with the current chapter number, an underscore, and the chapter, section, or subsection in one word and lowercase, followed by either “:cha” or “:sec” to specify what kind of label it is. These labels can then be used for references which will show the correct chapter and section number even after making changes. For example, if you have defined a section \section{Chapters and Sections}\label{c14_chaptersandsections:sec}, you could write We will discuss chapters and sections in Section \ref{c14_chaptersandsections:sec} which results in the document as “We will discuss chapters and sections in Section 14.4.”

Tables

In LaTeX, tables are like images and put into the figure environment (\begin{figure}…\end{figure}). As such, they have a caption, label, and positioning. Drawing a table like Table 11.3 requires a bit of coding:

 
 
\begin{figure}[H]\centering 
\ifxetex 
\resizebox{\textwidth}{!}{% 
\begin{tabular}{p{3cm}|p{6cm}|p{6.5cm}} 
\else 
{\begin{tabular}{c|c|c} 
\fi 
\hline 
&\textbf{Word}&\textbf{LaTeX}\\\hline 
Editor&‘‘what you see is what you get’’&source file is compiled\\\hline 
Compatibility&dependent on editor&independent of editor\\\hline 
Graphics&simple inbuilt editor, mouse-based&powerful but complex editor, text-based\\\hline 
Typography&optimized for speed&optimized for quality\\\hline 
Style&inbuilt style&separate style document\\\hline 
Multi-platform&only via export&possible with scripting\\\hline 
Refresh&some elements need manual refresh&everything is refreshed with each compile\\\hline 
Formulas&basic support needs external tools&complete support\\\hline 
 
\end{tabular}} 
\caption{Comparison of Word and LaTeX} 
\label{c1_comparisonwordlatex:fig} 
\end{figure}  

This table has the familiar figure, label, caption, and centering commands. The actual table is configured with the tabular environment. Following the tabular command, you configure the columns in curly braces. Each column is separated with a vertical line and the p{…} entry specifies the width of the column. With {p{3cm}|p{6cm}|p{6.5cm}}, you would have three columns with 3cm width for the first column and 6cm and 6.5cm width for the two others. Alternatively, you can use c instead of p{…} and leave out the curly braces with the width. Then, LaTeX simply calculates the required widths automatically (this is the preferred method for an e-book).

Then, for each line of the table, simply write content of the first cell&content of the second cell&content of the third cell\\\hline. Please be sure to use \hline in tabular environments, and \hrule outside of them.

E-Book / PDF Specific Content

To activate content only for either HTML output (e-book) or for PDF output (print), simply surround the code 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:

 
 
\begin{figure}[H]\centering 
\ifxetex 
\adjustbox{max width=.95\columnwidth, max height=.4\textheight}{ 
\input{images/philosophy-hierarchy.tex} 

\else 
\includegraphics{images/philosophy-hierarchy.png} 
\fi 
\label{c1_ontology-epistemology:fig} 
\end{figure}  

This includes a vector graphic (images/philosophy-hierarchy.tex for the PDF output, and a PNG image file for the HTML output.

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:

 
 
\ifxetex{} 
2016, First Edition 
\textsc{ISBN} 978-3-945586-21-1 
Printed on acid\hyp{}free, unbleached paper. 
\else{} 
E-book 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!} 
\fi{}  

This shows the edition number, ISBN, and paper quality for the PDF output, and the creation date and a note about how to rate the book for the HTML output.

A further example is footnotes. As e-books do not have pages in the traditional sense, your footnotes would end up in the appendix of the book at the end. 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 \textit{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{}  

This shows “Interesting to note here is the theory that every person in the world is connected to every other person by approximately seven intermediate connections [cf. Travers and Milgram1969].” as a footnote for the PDF output, and “[…] close acquaintance (interesting to note here is the theory that every person in the world is connected to every other person by approximately seven intermediate connections, [cf. Travers and Milgram1969]).” for the HTML output.

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:

 
 
\ifxetex{}\label{epicurus-philosophy-quote}\else{}\citep[p.~53]{epicurus}\fi{}  

Footnotes

Finally, for footnotes, there is the command \footnote. You can place it anywhere you like; LaTeX will then automatically add the number of the footnote at that place and put the footnote text into the footer area. For e-books, it is recommended to just use regular parentheses. This can be accomplished with the \ifxetex{} command. In the generated book, it looks like this (this is a footnote).

 
 
\ifxetex{} 
    .\footnote{This is a footnote.} 
\else{} 
    (this is a footnote). 
\fi{}  

Images

As in Word, in LaTeX, images are separate from the text. Images are usually packaged together with a caption and a label to reference the image from the text. These three entities are packaged together into a figure. The figure itself configures the size of the image as well as where it should be put. Let us look at a code sample:

 
 
\begin{figure}[H] 
  \centering 
  \ifxetex{} 
    \adjustbox{max width=.95\columnwidth, max height=.4\textheight}{ 
      \includegraphics{images/ebookLatex_Cover.png} 
    } 
  \else{} 
    \includegraphics{images/ebookLatex_Cover.jpg} 
  \fi{} 
  \caption{The cover of this book.} 
  \label{c1_cover1:fig} 
\end{figure}  
  • At the core is the image, included with \includegraphics{filename}. It inserts the image specified by the “filename.”
  • In the example, there are two versions of \includegraphics, one for the print output (\ifxetex{}), one for the e-book. This way, we include either the larger, lossless PNG version or a smaller, lossy JPG version of the cover.
  • For the e-book, we do not need to provide any image size as the first output will be an HTML file with no boundaries.
  • For the print edition, we have a clear boundary, namely the page width.
  • With the \adjustbox command, we can adjust the image size according to the page width (\columnwidth) and page height (\textheight).
  • In this case, in order to align with the caption and be able to show two images on one page, we want an image to be generally at most 95% of the page width and 40% of the page height.
  • Below this \ifxetex{}…\else{}…\fi{} construct, there is the caption with its label.
  • LaTeX automatically numbers each figure, so in the text, we can later refer to it with \ref{c1_cover1:fig}, which prints out the number of the figure.
  • Finally, all these commands are centered with the \centering command and surrounded with the figure environment.
  • The [H] instructs LaTeX to try to place the image exactly where it is in the LaTeX code.

TikZ Graphics

For graphics, you can also include other TeX files that contain graphics or commands that use the inbuilt TikZ graphics generator. Due to its flexibility, I even recommend using TikZ to replace any of your existing diagrams that are PNG or JPG images, because:

  • TikZ graphics can very easily be changed (for example, in translations or for making corrections).
  • TikZ graphics are small and flexible. They can be easily scaled to any size and are directly integrated into your project (no time-consuming editing in an external graphics program necessary).
  • TikZ graphics look better. As vector graphics, they are sent directly to the printer, so we need not worry about readability.

If you want to create a TikZ graphic, simply create a new LaTeX file in the tex-images folder and include it with \input (replacing \includegraphics) where you want to. Then, do a Recompile to regenerate the TikZ file. If this does not work for some reason, you can also force their re-creation by deleting the tikz-cache directory and then recreating it by clicking on the second icon at the top left (New Folder). This removes the generated cached image files that do not show up in Overleaf itself.

For the format of the file itself, it is a series of TikZ commands surrounded by the \begin{tikzpicture}…\end{tikzpicture} environment. Discussing all the commands is beyond the scope of this book, so I recommend three options:

  • Check out the PGF manual at https://www.ctan.org/pkg/pgf. It has more than 1,100 pages of documentation of each command and corresponding examples.
  • Check out the example TikZ pictures from my two books Philosophy for Heroes: Knowledge and Philosophy for Heroes: Continuum in the tex-images directory of the template.
  • Send us descriptions/drafts of the graphics you need. We can help you to create any graphic at affordable rates. Contact us at [email protected]

This is an excerpt from Better Books with LaTeX the Agile Way. You can get a copy here.

Categories
LaTeX Publishing

Filling the Template

This is an excerpt from Better Books with LaTeX the Agile Way. You can get a copy here.

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.

One way to understand the structure of a book is to imagine how books were created before the digital age. Imagine different groups of people working on the book and handing over the results to the next group. At the beginning of this process, there is the core material that makes up most of the book: the individual chapters and sections. Those are surrounded by the front and back matter, which consist of several layers. The author hands the text of the chapters over to the editor, together with a note introducing his or her work (the preface). The editor adds the table of contents, the indexbibliographyquotation sources, and maybe an appendix (containing summaries from throughout the book), and hands the book over to the publisher.

The publisher adds information to the book, too. That is, first the publisher page itself with the year of publication, ISBN number, copyright note, and publisher name, and then a description of how the book was created and, for example, how the reader can contact the publisher with any questions (the foreword). All the parts are then put into an envelope (consisting of the series title and half title), and handed over to the cover designer. The cover designer creates the cover, and packages it together with the book into another envelope (consisting of the title page including the cover picture) and hands it to the printer.

With the overall structure in mind, let us look at each of the elements one by one, starting with the project title. After having opened the template project, on the left side in the project file overview, you can find the file output.tex. This is the entry point of the template (hence it is displayed in bold). If you ever want to change the output language to another language, you can adapt the file accordingly by changing the parameter of the babel package. For example, replacing american with ngerman activates the babelDE script, as well as some language-related formatting and sorting. In addition, you could add language-specific hyphenation rules here. For now, let us continue with the English setting.

Front Matter

In the left project window, click on the front folder. You will see a list of several files open. Here, select title.tex. This will be the first page of the document. Then, start editing the file and do the following tasks:

  • Replace “The Title” with your book title.
  • Replace “The Subtitle” with your book subtitle
  • Replace “Publishing Company, Location” with your publishing company’s name and location.

About the last point, if you do not own a company, put in your own name and address. Note that from a legal standpoint, this depends on the country in which you are publishing the book. Writing all the information down puts you on the safe side; if you want privacy, you have to check what is required by law (and perhaps consider a P.O. box).

We also need two cover versions, one for the e-book (low resolution) and one for print (high resolution). The reason is that (at least on platforms like Amazon) your profits for each e-book shrink depending on the file size. In 2019, this download charge was around $.15 per MB, so a 10 MB e-book would reduce your profit by nearly $1.50. For print, file size can be ignored and thus the image quality can and should be as high as possible.

Rename both versions of your cover (PNG and JPG) cover_highres.png and cover.jpg and upload them into the images folder. Alternatively, just upload your cover files and replace the entries in the title.tex file.

If you do not have a cover file, skip this step. We discuss cover creation in another article and the book.

To upload a file, click on images in the left project window, click on the arrow, and select Upload File. If the file already exists, it gets overwritten. The most straightforward approach is to rename your cover file to fit the existing template; otherwise you have to change the corresponding entry in the title.tex file.

Next, open front/half-title.tex. In the print edition, this comes after the title on page 3 of the book. Complete the following tasks:

  • Replace “The Title” with your book title.
  • Replace “The Subtitle” with your book subtitle.

If your book is part of a series, add a page showing the title of the series and listing all the parts (see front/series-title.tex). We will ignore that for now and assume it is a standalone book.

Next, open front/publisher.tex. This page is usually reserved for information about the book as a product. You should enter here when it was produced, by whom, and how someone can reach you. If you just fill in the following information, your work in this file is done:

  • Replace “Your company’s name” with your company’s name.
  • Replace “Your company’s location (city)” with your company’s location.
  • Replace “Your website’s URL” with your website’s URL (using https://).
  • Replace “Your email address” with your email address.
  • Replace “Edition” with the edition number (e.g., First Edition).
  • Replace “ISBN” with your ISBN.
  • Replace “Your editor’s name” with your editor’s name.
  • Replace “Your designer’s name” with your book cover designer’s name.
  • Add your image sources and icons, including their license type.
  • Replace “Your newsletter email” with your newsletter email.
  • Again replace “Your website’s URL” with your website’s URL (using https://).

Next is the dedication page (see front/dedication.tex). Here, you can thank people who helped you create the book. This page stresses that books do not stand alone, but build on other people’s work. When writing it, think of it as a letter you would send out to those people. Some people just write, “To my husband/wife/parents.” If you see it as but a chore and want to express your gratitude to those people in person rather than in writing, you can safely leave out the dedication page. In another article or the book, we learn how to rearrange, add, or remove whole pages or sections.

Another optional page is the epigraph page (see front/epigraph.tex). This page sets the theme for the book. This can be a quote, a picture, or anything you think could fit here. Here you can be creative and put some emotion into your book, even if it might be a dry book about LaTeX and project management. In my book Philosophy for Heroes: Knowledge , I have used the epigraph to introduce the reader to the summary boxes—insights into philosophy and linguistics—that I have put at the end of every section. They tell a meta-story. They are the icing on the cake. For your epigraph, consider whether you want to add a particular plot or theme to your non-fiction book. The epigraph page is the perfect place to introduce this concept.

Next comes the foreword (see front/foreword.tex). This is written by the publisher, or by you, with your self-publisher hat on. It should focus less on the content of the book but rather on the book production process itself. Encourage the reader to give you feedback and advise how he or she can contact you with an issue with the book, such as an error. Alternatively, the foreword can be written by an expert in the field, as a type of endorsement.

After the foreword, it is now up to you, the author, to introduce the book in the preface (see front/preface.tex). This can include how you arrived at the decision to write it, a personal note to the readers, and an “elevator pitch,” a short introduction telling the reader why this book is an essential read. Try to be personal and try to stay away from sales talk or corporate speech. Add a quote by your favorite author as a finishing touch.

This concludes the front matter of the book.

Main Matter

In the folder list in the project view on the left, you will see a folder named main. This is the place for the main content, with a separate file for each chapter. Inside the main folder, you will find firstchapter.texsecondchapter.tex, and thirdchapter.tex. Those are just example files which you can simply delete or rename after you have added your own text.

  • If you are starting your book from scratch, simply open main/firstchapter.tex, remove the default template text below \end{chapterpage} and start writing.
  • If you already have your whole book (or portions of it) ready in one big Word (or text) file, you need to separate the text by chapter and put each chapter into a separate file.
  • If you have already separated your book into individual chapters, each in its own file, proceed as outlined below.

For each chapter, create a new file in the main directory in Overleaf. Instead of calling them firstchaptersecondchapter, etc., it is best to give them the chapter number plus the actual name of your chapter (for example, I named the file of this chapter main/13-filling-template.tex). This way, you can more easily refer to or rearrange them later.

Once you have identified all chapters and created the files, you need to copy the text into each chapter file. For this, simply select the text of your chapter (including the title), and copy and paste it into the corresponding .tex file. There is a chance that the project will no longer (or only partially) compile after inserting your text. This can happen if your text already contains what Overleaf interprets as LaTeX commands. The most frequent issues are:

  • Percentage signs % They are interpreted as comments by LaTeX and are thus ignored. Replace them with “\%”
  • Curly braces { } They are interpreted as special commands by LaTeX. Replace them with “\{” or “\}”
  • Dollar signs $ They are interpreted as starting or ending a mathematical formula. Replace them with “\${}”
  • Underscores _ They are used in mathematical formulas. Replace them with “\_”

Please note that there is no simple way of copying the formatting (bold, italic, font size, lists, indentation, etc.) from Word to LaTeX. If you already have your text formatted in Word, check out Chapter 14 for how to format the text manually. For any future books, I recommended that you write them directly in Overleaf from scratch and use the LaTeX formatting as you write.

Chapter Organization

Next, take a look into main/firstchapter.tex again. Here, you see additional formatting at the top that defines the chapter title page. For each of your chapter files, copy and paste the following code to the top of your file:

 
 
\begin{chapterpage}{Replace with First Chapter Name}{c1_firstchapter:cha} 
 
\begin{myquotation} The perfect place for an introducing quotation.\par\vspace*{15mm} 
\mbox{}\hfill \emdash{}Famous Person\index{Person, Famous} 
, \citetitle{bibitem}\index{@\citetitle{bibitem}} \ifxetex\label{famousperson-bibitem-quote}\else\citep[p.~123]{bibitem}\fi 
\par\end{myquotation} 
 
\end{chapterpage}  

Then, you need to:

  • Replace “Replace with First Chapter Name” with your chapter title.
  • Replace “c1_firstchapter:cha” with your chapter title label (no spaces, only lower case letters).
  • Replace the quotation text, add the person’s name, and (if you have it) the bibliography item. If you do not have the source, remove the following line:  
     
    \citetitle{bibitem}\index{@\citetitle{bibitem}} \ifxetex\label{famousperson2-bibitem-quote}\else\citep[p.~123]{bibitem}\fi  

You can find more about this in another article and the book.

There are several approaches for how to organize the individual chapters and sections of your book. Personally, I prefer to divide my content into small (ideally independent) slices, with each slice providing the reader with some benefit (as discussed in Part I of the book).

Back Matter

The back matter of a book typically consists of two elements: references and connecting with the author:

  • By “references” I mean the glossaryquestions to reflect on about the book’s contents, a summary of the main points of the book, the index, a list of image and quotation sources, and the bibliography. Whether or not you want to include the glossary, the questions, and the summary of ideas depends on the book you are writing. The index is created automatically, but it will need some work within the text of the main matter of the book, which we also discuss in another article and the book. The same applies to the bibliography.
  • By “connecting with the author” I mean the “About the Author” section, information about your (or your publisher’s) other books, an optional section about how the book was created, and a polite reminder to your readers to leave a written review online. If you want to give the book a finishing touch, end with a short quote on the last page.

Let us go through the files of the template one by one. Open the back/author.tex file and:

  • Upload a high-resolution (author_highres.png) and a low-resolution picture (author.jpg) of the author into images folder.
  • Replace the quotation text.
  • Add a short text describing your motivation, your professional background, what you are currently doing, and how to contact you.

If you have other books published, the back/advertisement.tex is the place you can list them. In the template, replace “YOUR NAME” in the chapter title, replace or remove the pictures of the book covers, and replace or remove the descriptions of the individual book entries.

Next, you are free to use the text in back/amazon.tex if you like or adapt it to your own needs, depending on where you publish the book. This is a reminder for the reader to provide you (and potential future readers) feedback.

Beyond the cited works and your other books, you can also direct the reader to additional book recommendations to delve deeper into the subject. For this, use the command \nocite in the back/recommended.tex file and list the recommended books by their book id from your bibliography file.

If you want to tell a story about how you created your book (if you have not already done so in the preface), you can do so in the back/thebooksstory.tex. Use this chapter to summarize what you have learned while writing the book. This helps you to write better books in the future and might be interesting for the reader as well. Myself, I like to talk about what is going on in the background of what I do. It is up to you. The existing default text in the template describes to a reader how the book was created using the template and this book as a guide. Feel free to skip this one—we cover how to reorganize or remove individual sections in another article or check out the book for more details.

Finally, replace the quote in back/last.tex to leave the reader with something to think about.

What about the table of contents? While it is generated automatically in both LaTeX and Word, updating it in LaTeX requires no additional work. As the project files are fully compiled after each change, you do not even need to manually refresh the table of contents. We still have to organize and format the text you have pasted into the main matter of the book, though. Once that is done, your whole table of contents will show up in the output.

That is it! Your book is finished and we can now move on to polishing.

Chances are that through the copying and writing process, a few issues have come up. That is normal! Remember, LaTeX takes a little bit of time to learn. But once you know it, it flows naturally like normal writing—like a normal language. All it takes is patience. If you hit a wall, you can always create a new copy of the template and progress in smaller steps. Even better, use the backup and restore feature (top menu entry, History, see the book for details).

This is an excerpt from Better Books with LaTeX the Agile Way. You can get a copy here.

Categories
LaTeX Publishing

Generate Your First E-book

This is an excerpt from Better Books with LaTeX the Agile Way. You can get a copy here.

So… how do we use LaTeX? What do we need to install, set up, etc.? And just how do we use LaTeX to create an e-book? For now, we will focus on getting you started generating a PDF and e-book. In another article and the book, we go step by step through the process of copying your book from your text source (e.g., Word) to the template.

LaTeX Support

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

If you encounter any error or have a question about LaTeX as it is used 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, one of our LaTeX developers can help you out at an affordable rate. But most issues can probably be solved immediately and at no cost (“You forgot to close the parentheses,” “You need to load package X,” “Your graphics file is corrupt,” etc.). Simply contact us at [email protected] and we will see what we can do!

For general LaTeX questions, you can also check out the community at https://tex.stackexchange.com. If you post a brief (but working) example with LaTeX code with which you are having a problem, the community can usually provide high-quality advice.

Before we start, yes, setting up LaTeX the first time is more complicated than writing a letter in Word. But there are many solutions available that allow you to use LaTeX without much hassle. One of those solutions is Overleaf, which I am using for writing this very book (and all my other books). Overleaf is an online editor and project manager for LaTeX documents. It is available free for projects that do not require password protection. If you want to keep your LaTeX code private, I recommend the Pro upgrade which also adds full project history, access management, support for larger projects, and priority support.

Overleaf ⋅  Overleaf is an online editor and project manager for LaTeX documents. It manages your project with a versioning system and automatically compiles your LaTeX code into PDF and (with some help) HTML. It is free for public projects and does not require an installation or setup. You can get an account here: https://www.overleaf.com.

Overleaf requires no installation. Just register an account, use my template, fill in your text, and you are ready to download the necessary files for print book or e-book creation. If you are using a different LaTeX website or your own local installation, a different configuration might be required. To register an account on Overleaf, simply go to https://www.overleaf.com/register, enter your name and email, confirm the email, and log into your Overleaf account at https://www.overleaf.com clicking on Log In.

Copy the Template

If you do not want to use the template, check out the appendix 24 for instructions to add TeX4ht to your existing project.

Once you have your account, copy the template either by visiting https://tinyurl.com/ltxtemplate or by going to https://www.overleaf.com/latex/templates, searching for Book Template for Amazon KDP, Google Play, and Leanpub, and opening Book Template for Amazon KDP, Google Play, and Leanpub (e-book and PDF) and pressing Open as Template.

Once copied, any changes to the template will be applied to your own copy. It is accessible via your Overleaf project view (go to https://www.overleaf.com and click on Projects or go directly to https://www.overleaf.com/project); your new project should be listed there.

The template itself needs to be adapted of course—after all, it is your book, not mine. But for now, let us focus first on how to get from the template to a book.

So, navigate to your project view (https://www.overleaf.comProjects) and click on the new project Book Template for Amazon KDP, Google Play, and Leanpub. In the opened window, you should see a menu bar at the top with the Menu button that opens the options for the project. On the right, you will see a preview of the PDF output. Remember what I mentioned at the beginning of the book: LaTeX is not a “what you see is what you get” editor. Instead, whatever you write first has to be compiled into a PDF. Hence, you have the actual editing window in the middle (horizontally), and the separate output window on the right side of the screen.

Create a PDF

The template is set up to produce both HTML files and PDF files. The HTML files can later be converted into formats that can be read by, for example, a Kindle e-book reader. For now, let us first create a PDF output.

Figure 12.1: The project settings screen in Overleaf.

For now, click on the Menu button at the top left. A new panel shows up (see Figure 12.1). In the Settings section, click on the drop-down menu right of Compiler.

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 takes longer to compile with XeLaTeX than the more basic pdfLaTeX.

For now, we want the PDF output, so select XeLaTeX.

Switching here between pdfLaTeX and XeLaTeX allows you to switch between HTML output for e-books (pdfLaTeX) and PDF output for printed books (XeLaTeX) but requires you to recompile your project. For this, click on Recompile in the menu above the preview window on the right. If the compilation did not work, the document icon to the right of Recompile will show a red box with the number of errors and warnings. If no number is shown or if there are only warnings (yellow box), you can proceed with the download.

To download the PDF of the XeLaTeX output, simply click on the third symbol (Download PDF, the second symbol to the right of Recompile in the PDF view). You can also click on Menu on the top left, and click on PDF. Done! Your first PDF. This PDF could be used to upload to on-demand book services like Amazon’s KDP.

Please note that the PDF will need further polishing, such as configuring what content is shown on the left-side and on the right-side pages. We will discuss issues like this in Chapter 18.

Create HTML Output

For now, let us try out the HTML generation. For this, click on the Menu button at the top left, and this time, select pdfLaTeX in the Settings section, in the drop-down menu to the right of Compiler. Then, press Recompile in the right panel. Before continuing, wait until the compilation is finished. If you encounter a problem here (and a little red box with a number appears on the document icon right beside Recompile), feel free to contact me at [email protected]

Figure 12.2: The zip file with the HTML output can be downloaded in the “Logs and output files” screen at the very bottom.

Convert HTML to Kindle

For downloading the e-book, you have to actually download all the output files (clicking on the Logs and output files icon at the top of the right window, scrolling all the way down to Other logs & files, and selecting the allfiles.zip entry, see Figure 12.2). A download with the zip archive should start now. After downloading, extract that zip archive, and navigate to the main directory. There, you should find an output.html. That is your converted LaTeX document! Click it and the browser with the book template’s contents should show up. 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!

Now we need one final tool, namely the Kindle Previewer. Go to https://www.amazon.com/gp/feature.html?docId=1000765261 and scroll down to the download links. If the link is not available or if it is broken, simply search for Amazon Kindle Previewer using a search engine.

Once downloaded, start the installation, and then start the Kindle Previewer. There, select File / Open Book (see Figure 12.3) and browse to the directory where you have unzipped the files of the book. Select output.html and press Open. This starts the conversion process.

Figure 12.3: Importing the HTML file in Kindle Previewer to convert it into a MOBI format.

Depending on the book size, this might take a moment (“Converting your book to Kindle format”). Once finished, a virtual Kindle reader should show up where you can browse through your book. If you are fine with how the contents look, press File / Export in the menu, and press Export. For the name of the exported file, I recommend including the current date to prevent confusion when uploading (for example, bbwltaw-09032019.mobi). A message box should pop up that reads “Book is successfully exported here.” You can safely ignore the warning message “Enhanced typesetting is enabled for the book being previewed, but it is not supported in the exported file.” This refers only to the fact that any fonts you are using in the HTML file are ignored and replaced by the respective fonts of the e-book reading device. Now you have a MOBI file that you can use later to upload to Amazon’s KDP platform and release it directly as an e-book on Amazon. We will discuss the details later (see Chapter 20), but in essence, that is the entire publishing process, at least from the technical side.

Versioning

Before you continue: while you are learning LaTeX, you should create a backup whenever your project compiles successfully. You can click on History (top menu, see Figure 12.4), then on All history, then on View single version, then on Label this version, then enter a name for the backup.

Figure 12.4: Setting the name of the current version of the book for later reference.

It is best to name each backup by the milestone you have reached so that you later know at what point you have made the backup. For example, after polishing the files for an e-book release (but before polishing it for print), you could name it “e-book polishing complete.”

You can always go back to a previous version and compare the changes you have made. Click on History, then on Compare to another version, then on Labels, and then on a file in the list on the left side with a note “edited” right beside it. That being said, you do not have to save as you write. Your latest changes are always saved automatically.

This is an excerpt from Better Books with LaTeX the Agile Way. You can get a copy here.

Categories
Editing LaTeX Publishing Uncategorized

Comparing Word and LaTeX

This is an excerpt from Better Books with LaTeX the Agile Way. You can get a copy here.

What is magic for? What use is wizardry if it cannot save a unicorn?

Peter S. Beagle, The Last Unicorn [Beagle1991, cf. p. 187f]

Having written six books on topics including project management and philosophy, I have gained a great deal of respect for a well-written book. It is not enough to just have a stack of notes that you sort into chapters. It is not enough to spend a lot of time editing and organizing those notes. It will create a book, but is a book really what you wanted? It might sound a bit strange, but the goal of writing a book is not the book itself. It is that the book will be read.

Even the best technologies cannot save a unicorn—or make us better authors. They cannot tell us what to write. But they can help us to bring our imagination and ideas onto paper more quickly and efficiently. All you need to become a successful author is your mind, a pen, and paper. Everything you need to become a published author more quickly is in the following chapters.

Comparing Word and LaTeX

Everyone knows Word. However, “knowing” Word mostly refers to ease of use, as it is a “what you see is what you get” (WYSIWYG) text editor. But if I asked how, using Word, to refer to another document’s text block and add that as a citation in a footnote, most people would have to look on the Internet to find out how that could be done. While most of the functionality is available through icons, you still need to know where to look when something is not a standard command like those used in formatting, making lists, or choosing fonts.

Word ⋅  Word usually refers to Microsoft Word. Generally, it is used as an umbrella term for all word processors that directly show you what you will get as an end result (as opposed to first having to process the file). This approach is more intuitive, but it makes editing large projects very complicated.

In LaTeX (pronounced LAH-tekh or LAY-tekh), you instead create a text document which is then translated into an actual formatted document (your book). Formatting is done through commands you enter as text into the document. To write a LaTeX document, you never have to touch your mouse, as you can enter everything by keystrokes alone.

LaTeX ⋅  LaTeX is a typesetting system that works more like a compiler than a word processor. While initially complicated, LaTeX allows better management of larger projects like theses or books by splitting the document into sections: style, references, and text.

Word and LaTeX each have particular advantages:

If you know the commands, creating a LaTeX document will be quicker than writing a Word document. You never have to break your concentration to access a special command. Sure, there are shortcuts in Word, too, but those have to be learned as well.

Because all commands are part of a LaTeX document, you can edit your text on any device with any editor you like, while Word documents require an installed editor (well, Word) that does not show the formatting and control information.

The upside of Word is its automated grammar check. LaTeX online platforms like Overleaf provide spell checks, but no integrated grammar check. We will have to wait for future releases in that regard.

Word offers integrated basic graphic functionality for symbols while LaTeX has to rely on a rather complicated vector graphics engine.

Editing a Word document using different versions of the software might lead to compatibility problems and it will certainly not look the same in all versions. While there are collaborative online editors for Word, you are then on the same level as LaTeX online editors like Overleaf and you lose the ability to work on your document while on the road without Internet connectivity. Compatibility issues are especially problematic if you are co-authoring a book or working with an editor, or when relying on exact page numbers. Do not forget that books can exist for quite a long time. Will your Word file still work in 10 or 20 years when it’s time to release a new edition of your book or use parts of your book in a new book or article?

LaTeX’ more substantial post-processing of each change allows for much more complex algorithms, which provide you with better hyphenation and professional-looking typography—both features come out of the box and require little to no tweaking. In LaTeX, the document is processed in the background with a delay (a few seconds up to several minutes), while Word has to provide any change in real time, which requires that editing is optimized primarily for speed. While LaTeX updates the whole document with each committed change, you need to update some elements manually in Word (for example, the table of contents and the index).

In LaTeX, an element of the style of the entire document can be changed with a single line of code, while it takes 10 clicks in Word to change the style of a document. While Word does have a sophisticated versioning system, this applies only to the text itself. The style information (for example, the formatting of headers or footers) in Word is not part of the visible document. Hence, changes to the style are not directly visible in the document version history.

Versioning system ⋅  A versioning system is a tool to track changes to a document. That means you can go back and check what has been changed and by whom.

If your document contains graphics, processing Word files can become really slow, or the program might even crash. Why? Because while you are editing, all the images have to be cached somewhere, which takes a lot of memory. When editing LaTeX documents, images in the editor are visible only by their text reference and are only later—one by one—compiled into a PDF or e-book.

LaTeX is known for its beautiful typography. For example, it supports kerning (see Figure 11.1) and ligatures (see Figure 11.2), giving a typeface its finishing touch. Improved hyphenation, proper small caps, and proper justification are other features LaTeX offers that Word cannot do as well or without additional work.

Figure 11.1: Example of applying kerning to a typeface.
Figure 11.2: Example of a ligature.

While Word has several tools inbuilt that support multiple languages (dictionary, basic grammar check, special characters, etc.), it is not designed to handle multiple languages at the same time. If you want to produce, for example, a German and an English version of your book, the best advice would be to use two separate documents and translate and compare them paragraph by paragraph. In LaTeX, a single document can contain multiple languages. To create a multi-language project, you can put each paragraph of the second (or third) language below the original language. This makes translation work more manageable and reduces work for synchronization when making revisions. This is possible by a simple switch command that uses all entries marked with either one language or with another.

In LaTeX, you can add functionality to switch between e-book and print output without having to manage two separate documents. For example, my Philosophy for Heroes: Knowledge project produces four output files: the German e-book, the English e-book, the German PDF, and the English PDF. Even if your ultimate goal is to focus on the printed version of your book, merely having a more affordable e-book version will help to increase sales as it gives your readers a choice. Those who do not have a preference about reading your book in print or as an e-book might opt for the cheaper version rather than not buying your book at all.

Because LaTeX documents are compiled, you have the option to build your document not as one huge file like in Word, but as a collection of many files. As mentioned above regarding images, you can also include text files at any part of the document (as opposed to copying the whole text into one huge file). This makes it easier to divide the work and proceed section by section, as opposed to having to locate the part you are currently working on each time you open the document. It also makes rearranging sections easier: you no longer have to copy and paste pages over pages (never being sure if you have successfully copied everything and nothing was lost). Instead, you just move the reference to a section to another place. For example, let us assume you write a book about dogs and cats and first discuss dogs, then cats. In LaTeX, you would put each discussion into a separate file, and include them into your main file like this:

\input{main/aboutdogs} 
\input{main/aboutcats}

Moving your discussion about cats to the front is done by simply switching the position in the main file:

  
\input{main/aboutcats} 
\input{main/aboutdogs}

If your document contains formulas, LaTeX provides an entire scientific library of functions to edit and display them directly in the document. While you can create basic formulas in Word, for any complex mathematics you need to use a separate program to create and embed an image. Likewise, especially non-fiction books rely heavily on citation. To manage your sources in Word, you need a separate plugin or third-party program (like Citavi), while LaTeX supports the most widely used standard BibTeX for free, with no plugins required.

Citavi ⋅  Citavi is a plugin for Word (see https://www.citavi.com) to manage your bibliography and citations.

LaTeX is open source and free (even the online editor Overleaf is free if you can do without password protection), while you have to pay license costs for Word.

Figure 11.3: Comparison of Word and LaTeX depending on the complexity of the task: for natural sciences, anything more complex than articles takes more effort in Word; for social sciences, anything more complex than papers takes more effort in Word; for novels, book series take more effort in Word than in LaTeX.

Ultimately, it depends on your needs. If you want to write a complex document like a book, the advantages of LaTeX outweigh those of Word. If you want to quickly write a few pages, Word is superior. For longer and more complex books, LaTeX takes less effort (see Figure 11.3). In this book, I will help you to get your book done and published with LaTeX using the free template provided with the book.

WordLaTeX
Editor“what you see is what you get”source file is compiled
Compatibilitydependent on editorindependent of editor
Graphicssimple inbuilt editor, mouse-basedpowerful but complex editor, text-based
Typographyoptimized for speedoptimized for quality
Styleinbuilt styleseparate style document
Multi-platformonly via exportpossible with scripting
Refreshsome elements need manual refresheverything is refreshed with each compile
Formulasbasic support needs external toolscomplete support
Figure 11.4:Comparison of Word and LaTeX