Writing a Series

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.

As you have learned by now, LaTeX documents are projects consisting of a whole folder of files as opposed to everything being in a single file such as with Word documents. While this adds a bit of an overhead, this way of creating documents shines once your project gets larger—or when you work on multiple books. As opposed to fiction books, in non-fiction books you will encounter repetitions over the span of your series or your general field.

For example, in my philosophy book series, each book can stand on its own. This means I have to repeat some of the definitions, examples, or explanations from previous books. Sure, you can copy and paste it and are done with it. But managing books over a lifetime requires working in updates. What if you want to change something in your definitions? Will you be able to keep the texts identical? Or even for novels, you might want to bring out a new edition of a particular book. Will you manage several different author pages, publisher information pages, advertisement pages, and so on?

Once you become proficient with your work, you will have to advance one level and manage your content. LaTeX projects offer the solution for this: you can simply link files of another project to yours and insert it seamlessly. The way to do it in Overleaf is this:

  • Select the folder where you want the file to be linked to.
  • Click on the arrow right of the folder name and select “Add…” and “File from other Project.”
  • Select the project, and then the file you want to link.

Once linked, you can use the file like a normal file in your project. Linked files show a different icon (a small chain) and you can simply access them via “\input{folder/file}”. You can of course also link images or any other type of file and use it with the corresponding commands (e.g., “\includegraphics{folder/file}”).

There are some limitations by Overleaf to this approach, though. Those might be fixed in the future, but at the moment, you can edit the file only in the original project, and when edited in the original project, you have to go again into the menu and select “Refresh linked files.”

What are possible candidates for linking? Let us take a look at the template:

  • Whole sections if you create a new version of your book with a different focus.
  • The bibliography—imagine having like a single library for all your projects.
  • Individual glossary, idea, or question items.
  • Images in general.
  • Template style files (in the lib directory).
  • The htlatex tools (latexmkrchtlatex.cfg, and site.css).

For the latter two items (the template style files, and the htlatex tools), you might have to be careful when linking them and making changes as it might change the paging of all your projects that use the file. On the other hand, if you plan to create new editions with a new layout anyways, it is easier and less likely to cause errors to have all your style files in one place and make each change only once.

For example, let us assume you have five LaTeX projects and want to change the book size from 5.25”x8” to 6”x9”. If the style files are linked, you would need to make only one change in thelib/bookformat.tex file and refresh the other projects and you are done. Of course it means that the layout of all the books change, but that is what you wanted anyways.

So, ultimately, the benefit depends on your situation. I advise to simply keep this feature in mind, and start writing your first few books. Once you can see a possible benefit of reorganizing your books, start by creating a central main project in Overleaf which houses your shared bibliography, glossary items, and so on, and link to them in the individual projects.

Whenever you make changes to your general template settings, you no longer have to make changes in each project individually. Instead, you can change it in the central main project, and then just refresh all the linked files in each of your book projects for the changes to take effect. For example, you have found a spelling error in your bibliography. You can fix this issue in the central main project and have the other projects refresh their bibliography, instead of having to apply the fix to every single bibliography file of each project.

Did you know?

Please note, though, that this is just the outline of the general idea. If you are seriously considering managing all your books in Overleaf , you need to do some planning. If you need help with project management, how you can organize your ideas, and bring them to paper quickly, we can help! -→ Read more in Writing Better Books, the Agile Way 


Publishing on Google Play

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

While Amazon KDP is the current market leader, it might be worthwhile to also publish a book on other platforms. One alternative is Google Play where people can buy books directly from their pre-installed “Books” application on their Android smartphone (or online on their computers). The advantage of Google over other competitors is that many people already have a Google account and have added their payment information, so that shopping online becomes less of a barrier to purchase. Another point for Google is that fewer competitors offer their books there (compared to Amazon). This is partly due to the more complex initial setup and upload process which we will be discussing in this chapter step by step.

To publish your e-book on Google Play, you need to have your EPUB file ready, have or register a Google account on, and then register yourself as a publisher. Registering a Google account is straightforward, so we can move on to creating an EPUB file.

If you already have the e-book on Amazon KDP, make sure it is not (or no longer) in the “KDP Select Program” which prohibits the release of the e-book (or large parts of it) on other platforms.

  Creating EPUB Files for Google Play

To prepare for the epub conversion, the LaTeX code might need some cleaning up. Go through this checklist to make sure those issues are met. There might be issues beyond that; if you encounter any, let us know at If all else fails, you can also use the PDF output—with the downside that it is optimized for print (two-page view, fixed trim size, etc.) while the EPUB output can be adapted to the specific size, resolution, and page orientation of the reader’s device. You can also refer to Google’s checklist of how to make a book available online:

  • Do not use special characters (like colons) as the ID of entries in the bibliography.
  • Do not use the \url{} command for emails or other non-URLs.

Calibre   Calibre is a HTML to EPUB converter tool (see that also allows you to edit the metadata of the EPUB, add a cover image, and set the parameters of the conversion.

There are many free software tools to convert your HTML file into EPUB for Google Play. I recommend using calibre. After download and installation, start the “E-book management” program which shows your current library. To add a book, click on “Add books,” browse to your directory where you have extracted the zip file you downloaded from Overleaf , and select the HTML file. On the right side, you will see a default picture for the cover (we have not assigned any yet), as well as a list of “Formats.” As we have not converted the file to EPUB yet, ZIP is the only format we have.

Next, left-click on your book entry, and click on “Convert books.” On the top left, you will see the input file format (ZIP), and on the top right, you will see the output format (EPUB). If another output format is shown on the top right corner, click on it and select EPUB. All that is left to do is to fill the meta data and adapt the page setup—all other items are good at their default setting.

On the right hand side, you need to enter the title, author(s), publisher, series name, and series number. You can skip the large text field below—the book’s description can be filled out on the particular platform where you release the EPUB file and might need several revisions there.

Then, add the cover file you have created previously in Chapter 11 (Google Play does not have an inbuilt cover creator).

Next, click on “Page setup” on the left, and select “Tablet” from the “Output profile” list. This disables image scaling for the conversion, and the images will instead later be scaled according to the device the reader is using to read your book. While this increases the size of the EPUB file, it allows your e-book to be read on any device.

Then, click on “Search & replace.” This looks a bit cryptic, but we need to fix how tex4ht builds its links in the file. Insert the following string into “Search regular expression”:

<a id="\w[0-9]-[0-9]+doc"></a>

Leave Replacement text empty, and click “Add.” Clear the “Search regular expression” field and now enter:

<a id="chapter\*\.[0-9]+"></a>

and click “Add” again. These two rules will remove faulty links that will otherwise show up as errors by Google Play.

Finally, press OK, wait for the conversion to be completed, and click on EPUB to open the e-book reader and check if the conversion was successful. Now you have an EPUB file we can later use to upload to Google Play’s e-book platform and release it.

After you have added your book the first time, you can simply copy the meta data and the cover image from your previous versions. For this, simply right-click on an existing entry, select “Edit metadata,” “Copy metadata,” and then right click on the new entry, selecting “Edit metadata,” and “Paste metadata.” You will probably import your book several times while learning how to work with Overleaf and LaTeX, so this feature can be helpful.


Instead of waiting for Google Play to process and check your EPUB file, you can also use an EPUB validator like The downside is that it is more strict than the Google Play validator—the output of Calibri will show a number of issues accepted by Google Play:

  • Error while parsing file ‘value of attribute “id” is invalid’ The id of one of your bibliography entries contains a special character.
  • Referenced resource could not be found in the EPUB. This issue shows up if your \url commands are malformed (the URL does not start with “http”).
  • CSS selector specifies absolute position. This is an issue of Calibri and cannot be fixed but has no effect on the actual e-book read by your readers.

For reasons of optimization, Calibri splits the HTML file into parts. Thus, the line numbers shown both by Google Play as well as the EPUB validator relate to those split files, not your original HTML file. To access those split files, go to the Calibri output directory, right click on the EPUB file, and unzip it with WinZip (or another similar unzip program).

  Registering at Google Play

Google sets some limits on people registering as a publisher (or a self-publishing author). The first step is to fill out the form at

This is generally also the address you can return to if you get lost during the publishing process.

Click on “GET STARTED NOW” which leads you to a login page (if you are not already logged in Google) and then to the entry page (“Find new fans. Sell more books.”). Click on “online interest form” ( and fill out the “Google Play Books Partner Program interest form.” The fields are all straightforward, fill in your info, and then press “SUBMIT.” This submits a request to Google which will put you into a queue.

Please note that because publishing on Google Play is still in development, the links could change. If you encounter a broken link, let us know and we will get you on the right page.

After a week or so (that is how long it took for me, it might vary depending on when you sign up), you can enter your publishing company’s name and country. Once your details are entered, the terms of use are displayed. Read carefully about your rights and when payments are made. If you agree with the contract, check the boxes and continue. Next, fill out the form with the payment address, and continue again.

Note that it now takes additional time for Google to confirm the data you have entered. You can set up your book(s), but you cannot publish any until then. This activation took, for me, about a week.

  Managing Your Book Library

Finally, you come to the overview window. Click on “Book library” and then on “Add book.”

I recommend to simply use the automatically generated one from Google (GGKEY, a unique key like the ASIN on Amazon) which you can get for free. For the other settings, leave the defaults and select “Digital” (e-book) as the medium.

Did you know?

If you are releasing multiple editions of your book (for example due to updates) on multiple platforms, you might want to think about acquiring ISBNs and assigning one ISBN for each edition. This helps you to keep track what edition you have released where and makes it easier for authors to cite, or for readers to review, your work. -→ Read more in Writing Better Books, the Agile Way

Next comes a series of forms that are similar to the ones to set up your book on Amazon KDP. If you have already entered your book on KDP, you can simply copy and paste most of the information (title, description, about the author, series, etc.). Once the meta data is entered, you can move on to the next item and upload your EPUB file. After the upload is finished, the file is automatically scanned for issues (this might take an hour or two). If you encounter any error messages, read again Chapter 12.1 or let us know at But if you have not made any major changes to the template, your file should be ready to be released. If you have just set up your account, you might still have to wait a while.

Before releasing the book, you might want to add yourself (or your editor) as a quality control inspector at the bottom of the “Contents” screen using your Google mail address.

The book will show up at of your Google account (or in the books application on your smartphone).

Once released, you can find your book by going to and search for the title of your book. That is it!

Did you know?

While marketing a book on Google Play takes somewhat more effort than on Amazon, Google also offers prominent display of your book on the Google search results page (see Figure 12.1). -→ Read more in Writing Better Books, the Agile Way 

Figure 12.1:Google Play books are displayed prominently on the Google search results page.


How to Create Cover Graphics

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.

Cover graphics are separate from the LaTeX project. You can neither create a cover graphic in LaTeX nor include it in your project. Instead, you need to use an external program to design it.

While Amazon (and other platforms) offer automatically generated covers, I strongly recommend not using them for your final publication. They are fine if you just need any cover to get your book printed and have a physical copy, but may well turn people away because they think the (lack of) effort you put into the cover reflects on the content of the book.

Unfortunately, I can give you only a technical guideline and some ideas. I recommend hiring a designer to produce the final version. Still, if you are somewhat proficient with a graphics editor, the following sections can give you at least a start. If you do not plan to publish a print edition, simply skip to Chapter 11.2.

 Download KDP Template

A cover consists of the front cover, the back cover, and the side, called the “spine.” Paperback cover are usually printed in one piece, meaning you need to provide an image with your back cover on the left, the spine in the middle, and the front cover on the right. Later, this print-out is folded and glued to the printed pages of your book. First, you need a template that fits the size specifications exactly. You do not want half of your front cover to bleed over into the spine or to have your text cut off at the edges. KDP provides a service for this, simply go to and enter the trim sizepage count, and paper color (which affects the thickness of each page and hence the width of the spine). For the trim size, use the same size as specified in lib/bookformat.tex. For the page count, use the actual page count of your PDF (which has nothing to do with the numbering you put into the book). Amazon will check your template, but not automatically, meaning you might lose a few days waiting for approval if your cover template does not match your PDF with the book’s content (for example if it shows a different title, or if the spine size does not fit the number of pages). Likewise, for the paper color, use the same setting you have selected previously in Chapter 10.2 in order to have the correct spine size. Once all is entered correctly, click on “Download cover template.” Note that the resulting template rounds your number of pages up to a multiple of 10. If possible, the best approach is to also align your content’s pages to a multiple to 10, but this is not required. There is a margin of error and KDP might decide to add empty pages. If your book has 251 pages (thus you need the 260 page template), you might want to check, though, if you can save a page somewhere. The template file contains both a PNG file and a PDF file. Depending on your graphics editor, choose the one with which you are most familiar. The template itself is self-explanatory: use the whole back cover space, spine space, and front cover space (including the areas marked red) for your back cover, spine, and front cover picture. Then enter your text while being careful not to touch any of the areas marked with red. The ISBN number on the back is added automatically, so be careful not to have any content in or near that area.

 Front Cover Structure

Did you know?

The front cover of your book is like the front of a shop: it is the one single thing with which you connect with possible readers. -→ Read more in Writing Better Books, the Agile Way

Concerning the front cover, note these two technical aspects:

  • If your front cover is white, you need to add small gray lines (maybe 3-4 pixels) around your template. This is because while the borders are clearly visible when the book is printed, the book cover preview on Amazon is displayed in front of a white background. Adding a gray border will make it stand out.
  • As a designer, you might be inclined to make it look as good as possible when you hold it in your hands. While this is a fine approach, the front cover also needs to look good (and readable!) when shown on the Amazon website. Try to scale down your cover and see if you can still recognize the writing and the image.

For the second point, let us look at the details currently at Amazon:

346 pixel height in the product page (where the customer decides to buy it or not).
218 pixel height in the search result page.
160 pixel height in the “Sponsored products related to this item” view.
115 pixel height in the “Shop by Category” view.

My proposal is that the following elements should be easily readable for the corresponding sizes:

(346 pixel height): Main title, subtitle, author name, ribbon, …
(218 pixel height): Main title, subtitle, ribbon.
(160 pixel height): Main title, subtitle.
(115 pixel height): Main title.

You might also have to use fonts that are easily readable at those sizes. This might reduce the quality of the high-resolution image and the printed cover but the only thing a potential buyer initially sees is the “minified” version of the cover. With printed books primarily sold in a (physical) book shop, the situation is different because customers can actually hold the final product in their hands: here, the details matter.

For the e-book cover, the process is the same as described above. The only major difference is that you are not bound by your selected trim size of the book. Instead, it is recommended by Amazon to use 2,560 x 1,600 pixels (1.6:1) aspect ratio). If your aspect ratio of the cover for your printed book is larger (meaning it has a smaller width), it might be worthwhile to create a new cover that makes use of this additional space.

I recommend saving the e-book cover as lossless PNG file. If you upload it to an online platform like KDP or Google Play, the platform will convert it automatically to the best format and resolution suited to each website.

 Back Cover Structure

The back cover is the text a potential buyer turns to after seeing the front cover. The reader now knows what the book is about and is deciding whether or not to buy it. Thus, the back cover is the place where you make the sale. You should list a more detailed description of the contents at the top, and a short author biography, ideally with a picture of you, in the middle. Unlike the front cover, there are no special requirements for the font sizes for the back cover. An interested reader will look at it in full resolution.

 Spine Considerations

The spine provides space for the book’s title and your name (rotated by 90 degrees). If your title is part of a series, you could put the series name here, too. Also, you might wonder how your book will book on the shelves in stores or libraries. There, your spine is the point of sale. If it is part of a series, you might want to go fancy and provide a nicely composed picture for when the books are arranged side by side.

 Cover Design

As mentioned above, it is recommended to have a professional designer work on your cover. Contact us at if you need help in that regard. If you want to select a freelancer on your own, I recommend hiring someone with whom you can communicate very clearly, as cover design goes beyond simple “Draw this,” “Here, I am done,” and “Thank you.” The designer needs to know what sets book covers apart from other graphics (like the different sizes of the cover graphic for advertisement discussed above). Ideally, the designer should have completed a number of past cover design projects. Examine his or her portfolio closely and do not expect that he or she will create a significantly better (or worse) design for your project.


Publishing on Amazon KDP

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.

Publishing on Amazon KDP is relatively straightforward once you have the MOBI file (for the e-book release, see Chapter 9), or the PDF file (for the print release, see Chapter 8) ready.

To start, head over to and click on “Sign in.” If you do not have an Amazon account, click “Sign up” and follow the instructions. When you sign in the first time, it creates a new KDP account and connects it to your Amazon account.

Personally, I use two different Amazon accounts, one for my personal orders, the other for anything related to publishing. For easier management, it is generally advised not to mix private and business accounts. You just have to make sure that when signing in, you are using the right account. If you are worried about the number of passwords you would have to manage, I recommend https://keepass.infowhere you can back up all your passwords safely and easily generate new ones.

Once signed in, you will see the main menu (“Bookshelf — Reports — Community — KDP Select”). Also, at the top, there is a link to “Help” ( which leads to a very detailed documentation of all the functions of KDP. If you are stuck, you can refer to that and easily find the solution. Alternatively, you are always free to contact us at!

 E-book Publishing

For now, click on Bookshelf. You will see a box “Create a New Title.” Click on “+ Kindle e-book.” Here, you have to fill out all the basic information about the book. Most items are self-explanatory, but I have a few comments on the following items:

  • Book Title. If the book is part of a series, include only the part title. For example, instead of putting “Philosophy for Heroes: Knowledge” into the box, just use “Knowledge” and put “Philosophy for Heroes” into the Series field. Changing the title after the release is possible, but needs to be done via Amazon support which can be notoriously slow or goes nowhere (as of 2018)—maybe that depends on your sales rank, though. An advantage of using the Series Title is that your other titles are referenced from each individual book product page.
  • DescriptionKeywords, and Categories. Enter the description, and the keywords that describe the contents of your work. Also, select two categories (as specific as possible) to categorize your work. These entries can be updated later, even after release.
  • Edition Number. This is optional. Use it only if you have already released a version and made significant updates to it.
  • Pre-order. The option to pre-order a book can be a significant marketing tool. For now, select “I am ready to release my book now”—even if you are not ready. It will not be released before going through all the steps, so do not worry.

Did you know?

Selecting the right keywords and writing a good description of your book is essential for marketing. One approach is to think about how to market the book at the very beginning of the project. -→ Read more in Writing Better Books, the Agile Way 

Press “Save and Continue” and continue to “Kindle e-book Content.” Here is where you upload your MOBI file (press “Upload e-book manuscript”).

While the file is processing, we can move on to the cover setup. While KDP offers a book cover creator, I strongly advise against using it. Book are sold by their cover and if your cover looks like you clicked it together in 10 minutes, people will think the book’s contents are of equally low quality. We will discuss cover creation in Chapter 11. If you already have a cover, select “Upload a cover you already have” and “Upload your cover file.” If you just want to test the publishing process, the cover creation process is straightforward. Start the cover creator, select a picture, select a design, and you are done.

Finally, once the cover is set, click on “Launch Previewer” to look at the produced e-book in your web browser. Alternatively, you can look at it directly on your Kindle (if you have one) or in your Kindle application on the computer or smartphone. Depending on your e-book size, it might take a while until the option becomes available.

If the upload went well and if there are no issues with the previewer, you could move on with “Save and Continue” and then publish your work on Amazon. That is it!

Let us now move on to how to publish a paperback on KDP.

  Paperback Publishing

Click on Bookshelf. If this is a new title (meaning you have not created a corresponding e-book title before), click on “+ Paperback” in the “Create a New Title” box. Here, you have to fill out all the basic information about the book. The form you have filled out is similar to what we have discussed above (Chapter 10.1). Press “Save and Continue” to edit the paperback’s content.

  • ISBN. The easiest choice is simply to select “Get a free KDP ISBN.” This comes at no additional cost. On the downside, if you ever move your book away from KDP, you cannot take your ISBN with you, which basically means you will have to create a new edition. If you decide to “Use your own ISBN,” you need to acquire a block of ISBNs. On the upside, your publishing company’s name shows up when using those ISBNs. Depending on the amount of ISBNs you buy and where you buy them, you can pay .50upto50 each. There are dozens of providers and comparing prices is recommended. Paying extra for additional services like bar codes is usually not worth the money. You can generate them yourself, and at least if you plan to publish on Amazon via KDP, bar codes are automatically generated. Plan for at least three ISBNs for each book in the long-term, as new editions (new size, hard-cover and soft-cover, changes within the book that moves content to different pages, etc.) each need a separate ISBN.
  • Publication date. Assuming you have not released this book earlier, leave it blank. If you have already released the book on another platform or by printing and selling it yourself, enter the release date here.
  • Interior & paper type. I recommend the option “Black & white interior with white paper.” A white background will improve the contrast for any graphics you are using. If you are creating a text-only book, you might consider “cream paper,” which is a bit more yellowish, heavier, and thicker. If you plan to use color graphics, select “color interior.” Please note the significantly increased cost for this print option ($18.35 instead of $3.85 per book as of 2018, see which reduces your profit margin. On the upside, you will have higher quality and thicker paper than with the black & white option. Some authors use this option even if they do not use any colored graphics. As with the cream option, selecting this option might influence your spin size and hence your cover template.
  • Trim Size. KDP offers a variety of trim sizes. Select the same size you have previously set in lib/bookformat.tex and when generating the cover template in Chapter 11.
  • Bleed Settings. Bleed refers to whether graphics are allowed to be printed beyond the usual print margin. The template does not use graphics reaching the margins, so select “No Bleed.”
  • Paperback cover finish. As an option, you can have KDP bind your book cover with a glossy foil. My recommendation is to check out both options in a test print. I prefer the “Matte” option as the foil of the glossy option can tear off.

Did you know?

Depending on the complexity of your book or book series, investing in ISBNs might be a waste of money. In a business, it is best to only invest when you know how exactly it can generate a return. -→ Read more in Writing Better Books, the Agile Way 

Next, upload the PDF of your book that you have generated in Overleaf .

Concerning the next step, the cover, the same applies as I have written above in Chapter 10.1: creating an own cover by a professional designer is recommended, but for test prints, using the KDP cover creator is sufficient. In case you already have a print-ready PDF cover (see also Chapter 11), press “Upload a cover you already have (print-ready PDF only).” Finally, click on “Launch Previewer” and do a final check of the contents as you have previously done with the PDF itself. In the previewer, take note of any warnings on the left side. If all is correct, press “Approve,” and move on to “Paperback Rights & Pricing” by pressing “Save and Continue.” There, you can set up the pricing.

Did you know?

Finding the right price for your book is just like finding the right content for your book. It is best to make it part of your marketing strategy right from the beginning. -→ Read more in Writing Better Books, the Agile Way 

Before actually publishing the book to Amazon, I strongly recommend ordering a proof copy by clicking on “Click here to request a proof copy” near the bottom of the page. Looking at a physical copy always gives you a different perspective on your work than seeing it on your screen.


Polishing for E-book Release

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.

Polishing for an e-book release is significantly easier than for a PDF print release. This is because the reading software or device where your book is displayed for the reader reformats your book to fit specifically on a particular screen.

Also, printed books have individual pages, while e-books do not. Your book’s contents are handled like a one-page website where you simply scroll from top to bottom. As there is also no index, once you have finished the last section, you are ready to release your texts as an e-book.

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 or creating the index, see Chapter 8 and Chapter 5).

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. In addition, text does not lose quality when being adapted to a certain screen resolution, while image quality might suffer significantly.

  Preparing Images for E-books

In contrast to what I have said in the previous section 8.3, for e-books, lossy JPG files are preferred because on Amazon, you will not pay by page, but by the file size of the e-book for each download. In addition, you should also use low resolution images (300 dpi) 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, if you want to provide an extra service for owners of more modern devices (or who read the book on smartphones), 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 328kb in color, but only 250kb in grayscale (see Figure 9.1).

Figure 9.1:An image of the Milky Way.

Another difference is scaling. For the print version, you are able to use \adjustbox to fit it into the width and height of the image. 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 in those cases where you have scaled down the picture in the PDF version. For all TikZ graphics, this was configured in the lib/inittikz.tex file (see Chapter 6.1.8): all TikZ graphics are automatically converted to PNG files with a fixed width (1245 pixels by default). Instead of being scaled up, the transparent background of smaller graphics is simply extended. For smaller graphics you include from external sources (JPG, PNG, EPS, PDF), you should make sure that they have sufficient empty 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. The benefit of this approach is that you do not need a separate e-book version of your images in order to ensure that fonts and lines have the same sizes and thickness throughout your book. This consistency improves the quality of your book.


Polishing for Print

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

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

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

 Clean up Empty Space

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

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

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

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

Left Hand / Right Hand Pages

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

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

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

 Clean Up Graphics

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

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

resolutionuseuse it with

Lossy JPG300-600dpie-booksphotos

Lossless PNG600dpiPDFphotos, diagrams

Vector graphicsn/abothgraphs, diagrams

Figure 8.1:Comparison of graphic formats and their application.

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

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

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

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

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

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

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

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

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


Converting LaTeX to HTML

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

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

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

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

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

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

  Switching from XeLaTeX to pdfLaTeX

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


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

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

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

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

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

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

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

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


  Tex4ht Configuration

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

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

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

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

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

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

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

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

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

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

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

  HTML Output Formatting

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

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

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

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

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

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

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

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

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

3. One way to highlight a quotation:

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

4. Adding small capitals textsc:

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

5. Have description list elements printed in bold:

dt.description { font-weight: bold; }

Template Management

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

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

  Template Library Files

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

  Packages File

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

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

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

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

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

 Language Selector

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

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

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


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

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

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

For example, look at this code:

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

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

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

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

 Book Format

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

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

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

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

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

Did you know?

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

Figure 6.1:Optimal leaf arrangement


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

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

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

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

  Chapter Design

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

For ease of use, you can use the command

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

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

  Header and Footer

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


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

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

  TikZ Initialization

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

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

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

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

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

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

Let us look at the details:

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

  Table of Contents

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

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


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

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

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

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

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


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

Biography —Name

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

Did you know?

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

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

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

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

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

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

  Core Files

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

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

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

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

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

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

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

 LaTeX Help

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

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

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


Index Creation

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.

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 only write an e-book version of your book, you can skip this section—e-books do not have indexes because they do not have fixed page numbers: they are formatted differently on different devices.

Did you know?

While an index for e-books is not needed, it can help tremendously with finding keywords for advertisement purposes. -→ Read more in Writing Better Books, the Agile Way

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

Beyond simply 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 book-making, 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

Figure 5.1:Marking an entry to add it to the index in Microsoft Word.

Word and LaTeX address each this issue in its own way. 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 5.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 the hidden symbol mode that shows things like line breaks or index entries which are usually hidden. In that regard, Word switches into a kind of hybrid mode, and you no longer “see what you get.” If you want to edit an index entry, you have to edit the code, for example “Mathematics{*XE*”language:mathematics”*}.”

  Indexing in LaTeX

In LaTeX, you insert the command in a straightforward way by adding the \index{…} directly into the text. For example, if you have the sentence “Mathematics is a language” you could add two indexes: “Mathematics\index{mathematics} is a language\index{language}.”

The big question is: which words should you index? Before we address that, let us look at an overall indexing strategy. Myself, I am using this one:

First, index all the terms that need to be indexed no matter what. Those are:

  • People names. Whenever you mention (or quote) a person, add the index command behind his or her name. The format for indexing people names 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.), it needs to be added at this position. If you mention the title directly, use “\index{title of the work@{title of the work}}”. Preferably, use the previously discussed “\citetitle{bibid}”: “\{@\citetitle{bookid}}”. The “bibid” stands for the id you have given in the bibliography file. The “@”-character is necessary for the indexing engine to recognize the italic font formatting. The exception to this rule 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).
  • Concept definitions. When introducing a concept and providing its definition (especially in glossary items), this is a place a reader might want to look first. For indexing, you can mark those indexes in bold by adding “—textbf”: “\index{word—textbf}”. For example:
    Science\index{science|textbf} is the formalized process of gaining new knowledge.
  • Captions. Do not index entries in 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. Now go from paragraph to paragraph and ask yourself each time what concepts this paragraph discusses.

It is not enough that a 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 no value from it. From the sentence, the reader does not get any explanation of what democracy is about. If the sentence was “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 is not a definition of democracy, so you would not mark it as bold in the index, but the sentence describes what democracy is. 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 “system of government” in your book, a reader will be satisfied reading the paragraph as—at least in its content—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 a longer 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 paragraph really explains the concept. If not, remove it.

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 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 into “alphabet, Greek”, “alphabet, Latin”, “alphabet, Phoenician.” This categorization can be done in LaTeX with the following construct:

\index{main category!sub category}. In our case: “\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. In addition, if you want to know more about the theory of knowledge and categorization of language and in philosophy, check out Philosophy for Heroes: Knowledge which explains it in detail.

Next, you might want to explain to the reader that two different words in the index actually refer 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 mathematicianLeonardo Bonacci is also known as Fibonacci. You might list both names and tell the reader that he is referring to the same person. If you used “Leonardo Bonacci” in your text, you can add an index 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 and check for spelling mistakes. These are common if your main tool of proofreading is the PDF or a printout because the index commands are hidden. The most common mistakes are having some index entries in singular form and some in plural, mixing British and American English, or having some expressions with and some without hyphens.

That is it!

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

Index all the basic terms (titles, people names, definitions).
Go through the entire text and index all the terms that are explained in a particular paragraph.
Check all indexes by going backwards from the index to the text.
Combine indexes into groups.
Check books with similar topics and get ideas based on how the authors did their indexing.
Add references from one index to another (e.g., for people with several names).
Check for spelling errors.

Bibliography and Citations

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.

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.

Myself, I love to know the source of an author’s ideas. This is basically the story of my book series Philosophy for Heroes, which is a summary of a number of philosophers and scientists I admire for their work.

Zotero   Zotero is a plugin for Word (see 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 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 ( which integrate 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/main.bib in the root directory. 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 All books have 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 fall under this category, for example websites or movies. 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 it is not possible to use the url field to set it to an Amazon affiliate link. This is prohibited by Amazon (see

  Getting Bibliographical Information

The simplest 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 BibTeX. This way, you can download an already filled-out bibliographical entry and copy and paste it into your bibliography/main.bib library. Finally, you want to know how to actually use the bibliography. The template is already set up to load the entries of bibliography/main.bib. With the following commands, you have access to the full library:

  • \citetitle{id} This command prints out the title specified in the corresponding entry in the bibliography. For example, “\citetitle{PFH1E}” cites my book Philosophy for Heroes: Knowledge in italics.
  • \cite{id} This command prints out the reference to the media and sets 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, there are many different formats that show a combination of year, title and / or author. If you want to use a different format, check out the documentation at