Categories
LaTeX

LaTeX Basics

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

This section will cover the basics of LaTeX so that you can make adjustments to your existing texts, understand the existing 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. The text in the affected line will be displayed in blue in Overleaf . In the template files, you will find a number of 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 marking it and pressing CTRL + B (in Overleaf ), or by surrounding it with the command \textbf{}.
  • Italics formatting. You can make your text italic by either marking it and pressing CTRL + I (in Overleaf ), or by surrounding it with the command \textit{}.
  • Small caps. You can change your text into small capitals by surrounding it with the command \textsc{}.
  • Em dashes. Em dashes are used to connect two related sentences. 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 it is not a “what you see is what you get” editor.
  • Empty line. If you want to force an empty line (recommended only in special cases), you can use ˜\\ (tilde followed by two backslashes).
  • New page. Pages are handled automatically by LaTeX. It tries to be smart in terms of positioning paragraphs and pictures. Sometimes it is necessary to add a page break, though (ideally, at the very end when polishing the final text). For that, simply add a \newpage.
  • Quotation marks. In the normal computer character set, there are more than one type 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) and refrain from using ”…” (or …) altogether. This is because Word’s … uses special characters, and ”…” do not mark the beginning and end of the quotation.
  • Horizontal line. For a horizontal line, simply write \hrule.
  • Underlined text. It is generally not recommended to use underlined text.
  • 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}”.
  • Special characters. If you need special characters or mathematical formulas, there is a whole body of work on that subject. It is not in the scope of this book to provide you 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}
          
    
  • 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 to have it start 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 like we used previously for the images. For example, if you have defined a section “\section{Chapters and Sections}\label{c1_chaptersandsections:sec},” you could write “We will discuss chapters and sections in section \ref{c1_chaptersandsections:sec}” which results in the document in “We will discuss chapters and sections in section 3.4”.

  Tables

In LaTeX, tables are like images and put into the figure environment. As such, they have a caption, label, and a positioning, as we discussed above with the images. Drawing a table like Table ?? (see Chapter ??) 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 \textit{Word} and \textit{LaTeX}} 
\label{c1_comparisonwordlatex:fig} 
\end{figure}
 

This table from the beginning of the book 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 (the preferred way for the 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, while \hrule outside of them.

  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 normal parentheses. This can be accomplished again with the \ifxetex command.

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

In the generated book, it looks like this (this is a footnote).

  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 it 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_cover:fig} 
\end{figure}
 

Let us go through this line by line.

  • At the core is the image, included with \includegraphics{path to file}. It inserts the image specified by the “path to file.”
  • 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 a 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 and the label.
  • LaTeX automatically numbers each figure, so in the text, we can later refer to it with “\ref{c1_cover: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.

Figure 3.1:The cover of this book.

In Figure 3.1, you can see the result of the command.

Instead of graphics, you can also include other TeX files that contain graphics (or commands to draw graphics, see Chapter 3.8).

 TikZ Graphics

For graphics, you can use the inbuilt TikZ graphics generator. Due to its flexibility, I even recommend images you already have for a number of reasons:

  • TikZ graphics can very easily changed (especially for for example translations or 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 are sent directly to the printer, 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 from scratch” by clicking on the top right corner of the preview window (showing Warning or Error) to regenerate the TikZ file. If “up-to-date and saved” is shown, delete the tikz-cachedirectory and recreate it. This deletes 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 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 is more than 1100 pages full with documentation of each command and corresponding examples.
  • Check out the few example TikZ pictures from my two books Philosophy for Heroes: Knowledge and Philosophy for Heroes: Continuum in the tex-images directory.
  • Send us descriptions / drafts of the graphics you need. We can help you at affordable rates. Contact us at mail@lode.de.
Categories
LaTeX

Filling the Template

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

Now that you have walked through the whole “build chain” of creating documents with the template, you can start to add content to it. In this section, we go through each file of the template (https://tinyurl.com/ltxtemplate) to 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 where 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 themselves 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 its note to the book, too, describing 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 where it is finally printed.

With the overall structure in mind, let us look at all the elements one by one. Let us start with the project title.

After having opened the template project, on the left side in the project file overview, you can find the file english.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 German (or another language), you can click on the arrow right beside the file name and select “Set as Main File.” If you want to switch back to English, just click on the arrow right beside english.tex and select “Set as Main File.” 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 number of 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 the file size of an e-book should be as small as possible (large e-books cost more), while file size for print can be ignored and thus the image quality can and should be as high as possible.

If you do not have a cover file, skip this step. We will discuss cover creation in chapter 11.

Rename both versions of your cover (JPG and PNG) into “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.

To upload a file, click on the arrow right of “images” in the left project window, and select “Upload from Computer.” If the file already exists, it gets overwritten. The simplest approach is to rename your cover file to fit the existing template, otherwise you have to change the line 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, the 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 (with https://).
  • Replace Your email address with your email address.
  • Replace Edition with the edition number.
  • 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 the license.
  • Replace Your newsletter email with your newsletter email.
  • Replace Your website with your website (with https://).

Did you know?


Getting all the legalities right is part of a book project, especially when it comes to licenses, ISBNs, quotes, and images. -→ Read more in Writing Better Books, the Agile Way 


Next in line 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. Later we will learn how to rearrange, add, or remove whole page or sections (see Chapter 6.2).

Another page that is optional 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—special 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 own epigraph, consider whether you want to add a certain 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 yourself with your self-publisher hat on. It should focus less on the content of the book but rather 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 like an erroneous print. 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 basically an “elevator pitch,” a short introduction telling the reader why this book is important to 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 can 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 findfirstchapter.texsecondchapter.tex, and thirdchapter.tex. Those are just example files which you can simply delete or rename after you have added your own texts.

  • If you are starting your book from scratch, simply open main/firstchapter.tex, remove the default template text below “\end{chapterpage}”, and start typing.
  • 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 give each chapter a name.
  • 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 actual name of your chapter. This way you can more easily move them around later without renaming them. For example, in this book project Better Books with LaTeX , this chapter is called main/filling-template.tex.

Once you have identified all chapters and created the files, you need to copy the text to each chapter. For this, simply select the text of your chapter (including the title), and copy and paste it into the corresponding .tex file.

Next, take a look into main/firstchapter.tex. Here, you see additional formatting at the top:

 
 
\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}
 

For each of your chapter files, copy and paste the above printed template to the top of your file. 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{famousperson-bibitem-quote}\else\citep[p.~123]{bibitem}\fi
          
    

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 formatted text in Word, check out Chapter 3 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 right away.


Did you know?


There are several approaches for how to organize the individual chapters and sections of your book. The one you choose depends on your project management method. My preferred approach is to divide my content into small (ideally independent) slices, where each slice provides the reader with some benefit. -→ Read more in Writing Better Books, the Agile Way 


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 LaTeX commands. The most frequent issues are:

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

  Back Matter

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

By “references” I mean the glossary, questions to reflect on 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. I found it useful in my own book series Philosophy for Heroes to make it a little bit easier for the reader to understand the concepts. The index is created automatically, but it will need some work within the text of the main matter of the book, which we will also discuss later. The same applies to the bibliography (see Chapter 4).

By “connecting with the author” I mean the “About the Author” section, advertisement for your (or your publisher’s) other books, an optional section about how the book was created, and a reminder 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 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 put this information.

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 give 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 deepen 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, but then again, I also wrote this book about how to create books. 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 will later talk about how to reorganize or remove individual sections (see Chapter 6.2).

One last thing, what about the table of contents? Just as in Word, it is generated based on the chapters and sections you have defined, so no work is required. As the project files are fully compiled after each change, you do not even need to refresh the table of contents manually. 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.

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

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 explained at the end of the previous Chapter 1 (top menu entry “HISTORY & REVISIONS”).

Categories
LaTeX

Generate Your First E-book

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

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. Later in Chapter 2, we will go step by step through the process of copying your book from your text source (e.g., Word) to the template.

As these are possibly your first steps in the world of Overleaf and LaTeX, feel free to contact me at mail@lode.de if you encounter any problems!

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 in writing this very book (and all my other books). It it available free for projects that do not require password protection. For professional books, I recommend the Pro upgrade which also comes with full project history, access management, support for larger projects, and priority support.

Overleaf requires no installation. Just sign up, 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 necessary.

The first thing you will need is an account on the online platform Overleaf Overleaf is an online editor and project manager for LaTeX documents. For this, simply go to https://www.overleaf.com/signup, enter your name and email, confirm the email, and log into your Overleaf account at https://www.overleaf.com clicking on “SIGN IN.” (if you want to help me hosting future templates and projects, use this instead: https://www.overleaf.com/signup?ref=506f081f3617)

Clone the Template

Once you have your account, grab a copy of 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 and Google Play,” and opening “Book Template for Amazon KDP and Google Play (e-book and PDF)”, and pressing “OPEN AS TEMPLATE.” Please note: Overleaf is currently updating its interface. As this is still ongoing, please use the old editor by selecting “No thanks, open in Overleaf v1 editor.” Once the update is complete (early 2019), I will update this book accordingly. As of now (September 2018), e-book export is not working properly. For the most up-to-date information about Overleaf v2, check https://www.lode.de/template. Once cloned, any changes to the template will be applied to your own copy of the template. It is accessible via your Overleaf project view (go to https://www.overleaf.com and click on “My Projects”); 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.com, “My Projects”) and click on the new project “Clemens Lode’s LaTeX Book Template.” Then, click on the project. If you are asked whether to port it to v2, select “No thanks, open in v1.” In the opened window, you should should see a menu bar at the top. Clicking on “PROJECT” closes or opens the file overview on the left. 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 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 1.1:The project settings screen in Overleaf .

For now, click on the settings icon (the wheel) at the top right of the screen. A new window shows up (see Figure 2.1), in the “Advanced Build Options,” click on the drop down menu right of “LaTeX Engine.”

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).

Once selected, click on “SAVE PROJECT SETTINGS.” Switching between pdfLaTeX and XeLaTeX requires a “recompile from scratch.” If a red error window shows up, select “recompile from scratch.” If all is fine, it should show “up-to-date and saved” and you can proceed with the download.

To download the PDF of the XeLaTeX output, simply click on PDF in the top menu. Done! Your first PDF. This PDF could be used to upload to on-demand book services like Amazon’s KDP. We will discuss this later.

Please note that the PDF will need further polishing, for example to configure what content is shown on the left hand and on the right hand pages. We will discuss issues like this in Chapter 8.

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).

Create HTML

For now, let us try out the HTML generation. For this, click again on the settings icon on the top right, and in the “Advanced Build Options” right of “LaTeX Engine,” select pdfLaTeX this time, and press “SAVE PROJECT SETTINGS.”

Before continuing, wait until the compilation is finished. A red error message should pop up (if it does not, you can skip to the next paragraph). Simply press “recompile from scratch” and you should be good to go. Wait until the compilation is done and either “warning” or the message “up-to-date and saved” shows up and you can proceed with the download. If you encounter a problem here, feel free to contact me at contact@lode.de.

For downloading the HTML file, you need to have your project window on the left opened (click on “PROJECT” in the menu bar if it is not open). Scroll all the way down to “DOWNLOAD AS ZIP” and click the small arrow near the bottom (see Figure 1.2). Wait until any ongoing compilation is done, then select “Input and Output Files,” and after a short while, a download with the zip archive should start. Extract that zip archive and navigate to the main directory. There, you should find a english.html. Click it and the browser with the book template’s contents should show up.

Figure 1.2:The zip file with the HTML output can be downloaded on the left side at the very bottom.

Convert HTML to Kindle

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

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” in a search engine.

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

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 the contents, press “File / Export” in the menu, and press “Export.” 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 we 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 10), but in essence, that is the entire publishing process, at least from the technical side.

Versioning

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

Before you continue: while you are learning LaTeX, you should create a backup whenever your project compiles successfully. You can click on “HISTORY & REVISIONS” (top menu, see Figure 1.4), enter a name of the backup in the “label current version” field, and press “ADD LABEL.”

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

You can recover a previous version by simply clicking again on the “HISTORY & REVISIONS” entry in the top menu, and then click on “restore” in the corresponding line of the previous backup. That being said, you do not have to save as you write. Your latest changes are always saved automatically.


Did you know?


Overleaf really shines in collaboration with another author or your editor. Using labels for different versions can help to speed up the review process significantly.  Read more in Writing Better Books, the Agile Way

Categories
Editing IT LaTeX Productivity

How to Create a Kindle Ebook with LaTeX

The ebook is now available! Head over to Amazon to get a copy. 

Book publishing is easier than ever, and my favorite language to use to create books is LaTeX. The Amazon ebook upload platform (https://kdp.amazon.com) allows users to upload a variety of formats, but not for LaTeX or its product, a PDF. Why is that? The reason is that Kindle ebook viewers are not simple PDF viewers. Kindle takes the text and reformats it in a way so that it is easily readable and provides the customer a repeatable experience across a variety of books. PDFs, on the other hand, are fixed: no matter what viewer you use, page 37 of a particular book always looks the same.

How then can we use LaTeX to get a Kindle ebook published?

Instead of PDFs, the workflow will rely on HTMLs that are converted to MOBI files. The MOBI files can be imported by Kindle. The big advantage of this workflow is that you can use the HTML files to convert into other formats, such as posting on your blog (which typically requires the removal of all the LaTeX code and a reformatting).

But no worries, we will go through the workflow step by step. I first wanted to give you the big picture.

So, how do we create the HTML file? I am a fan of “one-click” solutions. Whatever we do, LaTeX should generate the final HTML file and we should not have to make any manual changes. This requires some work, but in the end, it is worth it!

For my setup, I am using Overleaf. It offers an online editor, a PDF preview, an automatic Git backup, and a LaTeX compiler on one single website. If you are using a different LaTeX website or your own local installation, a different configuration might be necessary.

Converting LaTeX to HTML

To convert LaTeX to HTML, we need a special compiler, TEX4HT. Unfortunately, TEX4HT only works with pdfLaTeX, not with XeLaTeX or LuaLaTeX. So, as an initial preparation of your existing LaTeX code, you might have to make it compatible to pdfLaTeX. If it is already compatible or if you are already working with pdfLaTeX, you can move on to the next paragraph. If not, you will need to: switch to pdfLaTeX in the project settings; add the ifxetex package; and surround XeLaTeX-specific code with a “\ifxetex … \fi” construction. Having this compatibility allows you to generate PDFs with XeLaTeX, and also produce HTMLs with pdfLaTeX when you switch the compiler settings.

TEX4HT itself needs no installation, as it is already part of the Overleaf setup. All you need to do is include it in your workflow. In Overleaf, this is done by adding a file named “latexmkrc” in the main directory of your project and adding a configuration file (you can find an example here).

First, let’s create the latexmkrc file in the main directory of your project:

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

All this does is override the way Overleaf names the compiler $pdflatex, calling it htlatex in addition to pdflatex, and writing the output of the compilation of htlatex to a new file called output.txt. It also references my.cfg, where much of the HTML configuration resides.

When the compilation has finished, the HTML file will not show up within Overleaf. Instead, you have to actually download the output files (use the drop-down menu at the bottom left in the project window). In the downloaded zip archive, you should check the output.txt for errors. If there are no errors, the HTML file should be in the same directory, ready for use! You can unzip the file, open it in a browser, and there is your ebook! On to step two!

Converting HTML to MOBI

The main tool we will be using (besides LaTeX) is the Kindle Previewer. To preview how your HTML will look on various Kindle devices, download the Kindle Previewer here. Besides previewing, it also converts the HTML to MOBI, which can be uploaded to the KDP website or to a Kindle. Generally, for a professional ebook release, it is recommended to get a set of Kindle devices for testing. With the Kindle uploader tool, you can easily send your MOBI files to a specific device.

Now, open the HTML file with the Kindle previewer. It might give you helpful compiler warnings for you to fix, as well as a conversion to MOBI. Once all is in order, you can browse through your ebook with different Kindle device simulators and, finally, upload the MOBI file to KDP.

But wait! It does not look right!

Now we have to go a little deeper. First, you may wish to review the design documentation by Amazon.

During the conversion, we lost page breaks, maybe some lines, spacing formatting, indentation, etc. The bad news is that there is no 1:1 conversion possible. The good news is that we can include our own .css file to correct a few issues and redefine some of the environments in LaTeX itself to make things right. I will talk about this in a later article. Here, I will talk only about a few instances I have encountered. For others, that is up to you, especially if you used custom formatting in your LaTeX document.

For example, the title sizes might need some fixing:

h2 {
    font-size: 1.5em;
    margin-top: 0.83em;
    margin-bottom: 0.83em;
    font-weight: bold;
}

h3 {
    font-size: 1.17em;
    margin-top: 1em;
    margin-bottom: 1em;
    font-weight: bold;
}

h4 {
    margin-top: 1.33em;
    margin-bottom: 1.33em;
    font-weight: bold;
}

h5 {
    font-size: 0.83em;
    margin-top: 1.67em;
    margin-bottom: 1.67em;
    font-weight: bold;
}

And—kind of a hack—if you dislike paragraph indents, this is the way to go for Kindle:

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

In LaTeX itself, you might also want to redefine some commands. The following will move your footnotes to the end of the ebook (if you don’t, they will be put into external html files which are not included in the ebook), add a new command “myrule” for horizontal lines, a new command “emdash” for em-dashes, fix semi-colons, and rewrite newpage to tell Kindle to insert a page break.

\ifxetex

\else
    \usepackage{endnotes}
    \let\footcite\citep
    \ifx\HCode\undefined 
        \def\myrule{\hrule}
        \newcommand{\emdash}[1][]{\hspace{0pt}---\hspace{0pt}}%

\else
        \def\myrule{\HCode{<hr style="clear: both" />}}
            \def\semicolon{\detokenize{;}}
            \def\emdash{\HCode{&\#8212;}}% 
            \renewcommand\newpage[1][]{\HCode{<mbp:pagebreak />}}
    \fi
    \let\footnote=\endnote
\fi

That is all for now, I will add a second part with more details (like the table of contents, additional design options, and the index) later. But with some luck, I hope you get your ebook working with these instructions! Feel free to ask questions in the comment section.