LATEX Cookbook - Sample Chapter
LATEX Cookbook - Sample Chapter
LATEX Cookbook - Sample Chapter
With this book, you will learn to leverage the capabilities of the latest document classes and explore the
functionalities of the newest packages. The book starts with examples of common document types and
provides you with tutorials for tuning text design, using fonts, embedding images, and creating legible tables.
Common document elements, such as the bibliography, glossary, and index, are covered with LaTeX's
modern approach. The example-driven approach of this book is sure to increase your productivity.
Visit LaTeX-Cookbook.net for gallery, downloads, and code.
LATEX Cookbook
LaTeX is a high-quality typesetting software and is very popular, especially among scientists. Its programming
language gives you full control over every aspect of your documents.
or a book
Design a letter, a CV, a presentation, a flyer,
or a large poster
Fine-tune text and layout, utilize fonts, and
design tables
and problems
problems efficiently
real-world problems
$ 44.99 US
28.99 UK
P U B L I S H I N G
Stefan Kottwitz
A
LT
X
Cookbook
E
P U B L I S H I N G
Stefan Kottwitz
Preface
LaTeX is a high-quality typesetting software and is very popular, especially among scientists.
Its programming language gives you full control over every aspect of your documents, no
matter how complex they are. LaTeX's large number of customizable templates and supporting
packages cover most aspects of writing with embedded typographic expertise.
With this book, you will learn to leverage the capabilities of the latest document classes
and explore the functionalities of the newest packages.
This book starts with examples of common document types. It provides samples for tuning
text design, using fonts, embedding images, and creating legible tables. Common parts
of the document such as the bibliography, glossary, and index are covered with LaTeX's
modern approach.
You will learn how to create excellent graphics directly within LaTeX; this includes creating
diagrams and plots quickly and easily.
Finally, the book shows the application of LaTeX in various scientific fields.
The example-driven approach of this book is sure to increase your productivity.
Preface
Chapter 3, Adjusting Fonts, helps you to choose fonts globally, and demonstrates how to
adjust them within the document.
Chapter 4, Working with Images, contains some recipes for including, positioning, and
manipulating images within LaTeX. After discussing the quality aspects, you will get to know
about the concept of floating figures for automated positioning to give well-balanced text
heights on pages.
Chapter 5, Beautiful Designs, helps you in adding background images, creating beautiful
ornaments, adding pretty headings, producing a calendar, and inserting symbols for computer
keys and menu items.
Chapter 6, Designing Tables, helps you to create good-looking tables. Specifically, it
covers creating a legible table, aligning numeric data, adding colors, shape, shading, and
transparency merging and splitting cells, and reading in table data from external files.
Chapter 7, Contents, Indexes, and Bibliographies, provides recipes for quickly starting and
customizing the table of contents, lists of of figures and tables, bibliographies, glossaries,
and indexes.
Chapter 8, Getting the Most out of the PDF, explores the capabilities of PDF, such as
metadata, PDF comments, and fillable forms. You will see how to combine PDF files,
how to crop margins, and how to optimize the output for e-books.
Chapter 9, Creating Graphics, contains recipes to create impressive graphics. We will start off
using modern packages for various purposes to create complete and useable graphics, such
as various kinds of diagrams and charts.
Chapter 10, Advanced Mathematics, explores one of the classic strong points of LaTeXits
excellent quality in typesetting formulas. That's why LaTeX is the most used writing software
in mathematics. When it comes to formulas, other sciences benefit from it as well.
Chapter 11, Science and Technology, deals with other sciences such as chemistry, physics,
computer science, and technologies such as electronics. This chapter will be an overview,
showing how LaTeX can be used in various fields using specific recipes.
Chapter 12, Getting Support on the Internet, starts with a guide to the most useful
Internet resources for LaTeX. This chapter will show you how to get help from the TeX
online communities.
The Variety of
Document Types
Documents can vary in size, format, sectioning, and design in general. You can use LaTeX for
any document type. In this chapter, you will find recipes for different kinds of documents.
We will specifically cover the following topics:
Writing a thesis
Designing a book
Creating a presentation
Writing a letter
Producing a leaflet
Introduction
LaTeX has been around for many years. Over time, developers and authors have contributed a
lot of extensions to the LaTeX code base.
These extensions include the following:
Document class: This is a style file which is the frame of your document. It usually
comes with meaningful default settings that can be changed via options when
loading it. Its macros can be customized by the \renewcommand command. It often
provides commands for authors to modify settings.
1
Package: This is a style file with a specific purpose that can be loaded in addition
to the document class. Packages can be combined. Most of the time, we load many
packages using the \usepackage command.
Bundle: This is a set of closely related packages or classes. In our first recipe,
Writing a short text, you will get to know some bundles.
Template: This is a document filled with dummy text, which you can use it as
a starting point, and just fill in your own headings, texts, formulas, and images.
We will take a look at a template in our second recipe, Writing a thesis.
These add-ons are incredibly valuable! They are one of the reasons for the enduring success
of LaTeX. We all agree that learning LaTeX can be hard with its steep learning curve. However,
if you don't reinvent the wheel, and start with a good template or class and a quality set of
packages, you can quickly achieve great results.
The purpose of this book is to assist you in this regard.
Getting ready
To be able to work with LaTeX, you need install the following on your computer:
TeX and LaTeX software, which are together called TeX distribution
If you already have these installed, great! In that case, you can skip the next paragraphs and
immediately proceed to the first recipe.
A PDF reader is probably already installed on your computer, such as the Foxit Reader, the
Adobe Reader or the Preview app on the Mac. Furthermore, most editors come with an
integrated PDF previewer. So, let's take a look at the TeX software and editors.
MacTeX: This is based on TeX Live and has been significantly customized for Mac OS
X. The basic information is available at http://www.tug.org/mactex/.
Chapter 1
proTeXt: This is for Windows only, and it is derived from MiKTeX, but proTeXt is more
user-friendly during installation. Its home page can be found at http://www.tug.
org/protext/.
I recommend that you choose MacTeX if you have a Mac; otherwise, I recommend using TeX
Live, since the support by the TUG is especially good.
Describing the setup is beyond the scope of this book. For TeX Live, you can find a step-by-step
explanation with screenshots in the LaTeX Beginner's Guide by Packt Publishing. Generally,
when you visit Internet addresses of the TeX distributions listed above, you can find detailed
setup instructions.
Finally, on Linux, such as Ubuntu, Debian, Red Hat, Fedora, and SUSE versions, there's usually
a TeX Live-based software package available via the operating system repositories. While it's
usually not as up-to-date as an installation done via the TeX Live website or a TeX Live DVD,
it's very easy to install using the Linux package manager, which you use to install any software
usually.
LaTeX editors
There are many LaTeX editors, from small and quick to very feature-rich editors. The TeX
distributions already provide the fine editor TeXworks, which I use. It can be set up together
with TeX or with a package manager on Linux, and it can be downloaded from http://www.
tug.org/texworks/.
I have a collection of the links to LaTeX editors and additional software on my blog, http://
texblog.net/latex-link-archive/distribution-editor-viewer/, where you
may look for alternative editors, which run on your operating system.
Additionally, there are pure online LaTeX editors, which run in a web browser, so you can use
them even on tablets and smartphones. The most noticeable LaTeX editors are as follows:
How to do it...
We will start with a complete small document, already using various features. This can be your
template, into which you can add your own text later on.
While we go through the document step by step, you may open the complete code directly
with your editor, so you don't need to type it. It is contained in the code bundle available at
the book's page https://www.packtpub.com and at the book's page http://latexcookbook.net. Perform the following steps to create a small document:
1. Start with a document class. We will use the KOMA-Script class scrartcl, with
A4 paper size, a base font size of 12 pt, and interparagraph spacing instead of the
default paragraph indentation:
\documentclass[paper=a4,oneside,fontsize=12pt,
parskip=full]{scrartcl}
Chapter 1
4. Start a section without numbering:
\addsec{Introduction}
7.
Add a bulleted list using an itemize environment. Each list item starts with \item.
Using \ref{label}, we will refer to labels, which we will create later:
\begin{itemize}
\item a table of contents,
\item a bulleted list,
\item headings and some text and math in section,
\item referencing such as to section \ref{sec:maths} and
equation (\ref{eq:integral}).
\end{itemize}
9. Set a label so that we can refer to this point whenever we want to refer to this section:
\label{sec:maths}
10. Continue with the text. We will start using some mathematical expressions in the text.
We mark this by enclosing them in parentheses with a prefixing backslash, that is,
\( \).
When we write a scientific or technical document, we
usually include math formulas. To get a brief glimpse
of the look of maths, we will look at an integral
approximation of a function \( f(x) \) as a sum with
weights \( w_i \):
13. Compile the document. The first page of the output will look like this:
Chapter 1
How it works...
In the first line, we loaded the document class scrartcl. In square brackets, we set options
for specifying an A4 paper size with one-sided printing and a font size of 12 pt. Finally, we
chose to have a full line between paragraphs in the output so that we can easily distinguish
paragraphs.
The default setting is no space between paragraphs and a small indentation
at the beginning of each paragraph. Uncheck the parskip option to see
it. We chose a paragraph skip because many people are used to it when
working with e-mails, while indentation costs line space, which is a precious
resource on small electronic devices.
Without further ado, we began the text with a table of contents. While numbered sections are
started by the \section command, we can start unnumbered sections by using the starred
version \section*. However, we used the KOMA-Script command \addsec for the first
unnumbered section. That's because, in contrast with \section*, the \addsec command
generates an entry in the table of contents.
An empty line tells LaTeX to make a paragraph break.
As bulleted lists are a good way to clearly present points, we used an itemize environment
for this. All environments start with the \begin command and are ended with the \end
command.
If you would like to have a numbered list, use the enumerate environment.
Small formulas within text lines have been enclosed in \( ... \), which provides inline
math mode. Dollar symbols, $ ... $, can be used instead of \( ... \), which makes
typing easier. However, the use of parentheses makes it easier to understand where the math
mode starts and where it ends, which may be beneficial when many math expressions are
scattered throughout the text.
7
See also
The part of the document before the \begin{document} command is called the preamble.
It contains global settings. By adding a few lines to our document preamble, we can improve
our document and modify the general appearance. Chapter 2, Tuning the Text, starts with
additions that are beneficial for small documents as well. They enable the direct input of
accented characters and unicode symbols, and they improve justification and hyphenation.
In Chapter 3, Adjusting Fonts, you can find recipes for changing the fonts of either the whole
document or of certain elements.
For further customization tasks, such as modifying page layout, and adding a title page, refer
to the recipe Designing a book in the current chapter. We will take a look at such settings on
the occasion of a book example.
Writing a thesis
When you plan to write a large document like a thesis, you have two choices: either choose a
ready-made template, or set up your own document environment. If you have got limited time
and need to start off with your thesis fast, a template can come to the rescue.
Beware of outdated and questionable templates found somewhere on the Internet. Look
first at the date and at user opinions, such as on web forums. The age of a template is not
a problem by itself, as LaTeX can run it the same way when it's been written. However, as
LaTeX has developed, better solutions have come up over time. Legacy code may not benefit
from it.
Some universities provide their own templates. That may be ok, because requirements
would be met for sure; just check if it can be improved; for example, by replacing an obsolete
package with its recommended successors.
A very good source for checking the quality of a template is the guide to obsolete
commands and packages in LaTeX2e, which is also called l2tabu. You can open the
English version by typing the texdoc l2tabuen command in Command Prompt,
or by visiting http://texdoc.net/pkg/l2tabuen.
Chapter 1
To be clear, the LaTeX base is stable and solid, but there are changes in community-contributed
packages.
In the previous recipe, Writing a short text, we took the bottom-up approach and built a
document from scratch, adding what we desired. Now we will go top-down; let's use and
understand a complete template, removing what we don't need.
As we need to choose a template now, let's take a real gem. The ClassicThesis package
by Prof. Andr Miede is a thesis template of very good quality. The design follows the classic
guide to writing, The Elements of Typographic Style by Robert Bringhurst, we will see some
particular points later in this recipe. Its implementation is thoughtful and modern. Originally
written in 2006, it's maintained today as well, and shipped with TeX distributions.
Even if you would not use this specific template later, it shows how we can organize a large
document.
Getting ready
Though the ClassicThesis package may already be installed in your TeX system, named
classicthesis.sty, the whole template is an archive of files that should go into your
working directory.
Download the ClassicThesis archive from CTAN by visiting http://www.ctan.org/
tex-archive/macros/latex/contrib/classicthesis/.
Instead of fetching single files, choose to download it as a .zip file. Unzip it to where you
keep your personal documents, in its own directory. This directory will be your thesis directory.
This package provides a ready-made structured filesystem of the main document, style file,
settings file, and document parts such as the abstract and foreword, and also chapters in
dedicated files. You can edit all files and fill in your own text.
The ClassicThesis.tex file is the main document. Its filler text is the template's manual;
this allows us to compile the template immediately for looking at the output design. By
compiling, you can also verify that your TeX installation can handle additional packages
if you need to install any.
How to do it...
After unzipping, your directory will have the following structure:
10
Chapter 1
3. You can review and edit the settings in the main file, MyThesis.tex, and in the
configuration file, classicthesis-config.tex. Over the course of the following
pages, we will examine their content.
4. Open the existing .tex files, such as Abstract.tex and Chapter01.tex, with
your editor. Remove the filler text and type in your own text. Add further chapter files
as needed, and include them in the main file, MyThesis.tex, using the \include
command. The structure is given; the technical part of the editing is like cloning files
and copying lines, all you need to focus on is the actual thesis content now.
Don't worry if the font or margins don't please you yet. You can change the layout at any time.
Let's take a closer look now, and then you will know how.
How it works...
We will take a look at the functional lines of the main file, MyThesis.tex.
The document preamble is as follows:
\documentclass[ twoside,openright,titlepage,
numbers=noenddot,headinclude,
footinclude=true,cleardoublepage=empty,
BCOR=5mm,paper=a4,fontsize=11pt,
ngerman,american,%
]{scrreprt}
\input{classicthesis-config}
The template is built on the KOMA-Script class, scrreprt. KOMA-Script as a LaTeX bundle is
described in this chapter's first recipe, Writing a short text.
You can change the preset options to those you need, such as the font size or binding
correction BCOR. There are many class options for adjusting the layout; you can read about
them in the KOMA-Script manual. Type texdoc scrguien in Command prompt, or visit
http://texdoc.net/pkg/scrguien. We will discuss some of them in depth in our next
recipe, Designing a book.
Loading of packages and all the remaining settings is done in a single file, classicthesisconfig.tex. We will look at it later in this recipe.
The document body starts with the following commands:
\begin{document}
\frenchspacing
\raggedbottom
\selectlanguage{american}
\pagenumbering{roman}
\pagestyle{plain}
11
Each commonly-required part of the front matter has its own file. Just edit the file as you need
it, comment out by inserting a % symbol at the beginning of a line, or remove what you don't
need. The \cleardoublepage line ends a page, but also ensures that the next page starts
on the right-hand side. This can mean inserting an empty page if necessary; that is, a double
page break. This will not happen if you change the twoside option to oneside, so you can
keep the \cleardoublepage line, which will act like a \clearpage command when the
oneside option is set.
Finally, we got the main matter:
\pagenumbering{arabic}
%\setcounter{page}{90}
% use \cleardoublepage here to avoid problems with pdfbookmark
\cleardoublepage
\part{Some Kind of Manual}
\include{Chapters/Chapter01}
\cleardoublepage
12
Chapter 1
\ctparttext{You can put some informational part preamble text
here...}
\part{The Showcase}
\include{Chapters/Chapter02}
\include{Chapters/Chapter03}
In the main matter, we use Arabic page numbers. The \pagenumbering line resets the page
number to 0.
The thesis is divided into parts. Each one is split into chapters. You can omit the \part lines
if you want your highest sectioning level to be the chapter level.
In the Chapters subdirectory, each chapter has its own .tex file; so, you can easily handle a
large amount of text. Furthermore, you can use the \includeonly command to compile just
the selected chapters for speeding up writing.
Finally, the main document ends with the back matter:
\appendix
\cleardoublepage
\part{Appendix}
\include{Chapters/Chapter0A}
%*****************************************************************
***
% Other Stuff in the Back
%*******************************************************
\cleardoublepage\include{FrontBackmatter/Bibliography}
\cleardoublepage\include{FrontBackmatter/Colophon}
\cleardoublepage\include{FrontBackmatter/Declaration}
\end{document}
The command \appendix resets the sectioning counters and changes them to alphabetic
numbering, that is, the following chapters will be numbered A, B, and so on. Like in the front
matter, the parts of the appendix are divided into several files.
Let's take a look at the configuration file. Open the classicthesis-config.tex file.
The whole thing would take too much space in the book, so let's just take a look at some
sample lines:
\newcommand{\myTitle}{A Classic Thesis Style\xspace}
\newcommand{\myName}{Andr\'e Miede\xspace}
\newcommand{\myUni}{Put data here\xspace}
\newcommand{\myLocation}{Darmstadt\xspace}
\newcommand{\myTime}{August 2012\xspace}
13
There's more...
As mentioned, this template contains design decisions inspired by the book The Elements of
Typographical Style by Robert Bringhurst. The most notable design decisions are as follows:
It doesn't use bold fonts, but rather uses small caps or italics elegantly to emphasize
what's important.
The text body is not very wide and this allows it to be read comfortably without
needing the eyes to jump too far from the end of the line to the beginning of the next
line. So, we have wide margins, which can be used for notes.
The table of contents is not stretched to get right-aligned page numbers. To quote the
author, "Is your reader interested in the page number or does she/he want to sum the
numbers up?". That's why the page number follows the title.
This is another way of setting the input encoding. Refer to the recipe Inputting accented
characters in Chapter 2, Tuning the Text, to understand the topic of encoding. Here, you
should change the latin9 option to utf8 if you wish to use an UTF-8-capable system and
editor. The latin9 option is typically used by older editors on Windows. There are other
encodings. If you would need another one, use texdoc inputenc, or visit http://
texdoc.net/pkg/inputenc to take a look at the available options.
14
Chapter 1
Here, you can find the options for the actual classicthesis package. Simply add
the dottedtoc option to this comma separated list. These options, among others, are
documented in the template's manual. You can open it by typing texdoc classicthesis in
Command Prompt, or at http://texdoc.net/pkg/classicthesis. (editor: please apply
inline code formatting correctly, and URL formatting)
Here, you can also provide a value for the space that you leave for the binding and all margins
you like. It's good practice to have a visible inner margin set to half the value of the outer
margin, because margins will be added in the middle. For single-sided printing, with the
oneside option, use left=... and right=... for the defining the margins instead of
inner and outer.
Place such a line at the end of the classicthesis-config.tex file so that it will override
the original settings.
The template loads the caption package. It provides a lot of features for fine-tuning captions.
For now, the caption texts are indented so they will hang under the first line, and they will have
a smaller font size than the normal text. By adding simple options, you can further adjust the
appearance; for example, by adding the labelfont=it line, you can get italicized caption
labels. Refer to the caption manual to learn more. As usual, you can open it via texdoc
caption or at http://texdoc.net/pkg/caption.
15
With these ClassicThesis lines displayed equations will be left aligned. The fleqn option
allows switching to this alignment. If you would like to restore the default behavior, which is
centering the equations, remove that first line that passes the option, or comment it out by
a % symbol. But keep the second line, though, which loads the amsmath option, as this is
the de-facto standard package for typesetting mathematics in LaTeX.
You can find further thesis templates at http://www.latextemplates.com.
See also
In the following chapters, you can find a lot of recipes for content elements in your thesis. For
a beautiful thesis, elegant tables are of great value, so you may also want to take a look at the
Advanced table design recipe in Chapter 5, Beautiful Designs.
Designing a book
A book can be a pretty large document, so we can take a similar approach to the one we took
in the preceding recipe. Refer to that recipe to see how to split your document into handy files
and how to organize the directory structure.
Commonly, books are printed two sided. They are divided into chapters, which start on
right-hand side pages, and they have pretty spacy headings and often a page header showing
the current chapter title. Readability and good typography are important, so you will hardly find
books with an A4 paper size, double-line spacing, and similar specs, which some institutes
expect of a thesis. This is why we have dedicated book classes with meaningful default
settings and features.
16
Chapter 1
How to do it...
As explained in the Writing a short text recipe, our choice will be a KOMA-Script class; only,
this time it has the name scrbook.
Perform these steps to start off a book:
1. Start with the scrbook class and suitable options for paper and font size:
\documentclass[fontsize=11pt,paper=a5,
pagesize=auto]{scrbook}
2. Specify the input encoding, which will depend on your editor settings:
\usepackage[utf8]{inputenc}
4. If you want a nondefault font, load it. Here, we chose Latin Modern:
\usepackage{lmodern}
5. We will load the blindtext package to get English dummy texts. It also requires you
to load babel with the English setting:
\usepackage[english]{babel}
\usepackage{blindtext}
7.
Using this command, you can switch off the additional space after sentence
punctuation:
\frenchspacing
9. Provide a title, a subtitle, an author name, and a date. You can also set an empty
value if you don't want to have something in the title field:
\title{The Book}
\subtitle{Some more to know}
\author{The Author}
\date{}
17
12. We will divide this book in to parts, so start with the first part:
\part{First portion}
13. Start a chapter with a heading. It's good to have text before adding another heading,
so let's insert some:
\chapter{The beginning}
Some introductional text comes here.
14. As we did in our first recipe, add a section and text, and another part with a chapter
and section. Using the \Blindtext command, you can generate a long dummy text,
and using \blindtext, you can generate shorter dummy texts. The \appendix
command switches the font to alphabetic numbering:
\section{A first section}
Dummy text will follow.
\blindtext
\section{Another section}
\Blindtext
\appendix
\part{Appendix}
\chapter{An addendum}
\section{Section within the appendix}
\blindtext
16. Let your editor compile the text to PDF. You will get a 13-page-long book document
with A5 paper size, a title page, part pages, chapter, section headings, and filler text.
18
Chapter 1
Take a look at the following sample page:
Note the headings in sans serif font. This is an intentional default setting in KOMAScript classes, which makes the headings lighter than the standard LaTeX big, bold,
and serif headings. You may know the standard look.
17. Now, you can fill in your own text, add chapters and sections, and possibly add
features, which will be described later in this recipe.
19
How it works...
At first, we loaded the class scrbook, which was specifically made for writing books.
So, it is ready for two-sided printing with meaningful margins and good proportions of
headings and text.
Besides the class's default settings, we chose a font size of 11 pt and A5 paper size, which
is handy for a book. The pagesize=auto option is important here as it ensures that the
A5 printing area will be taken over to the PDF page size.
Then, we did the following things, which will be explained in more detail at the beginning
of Chapter 2, Tuning the Text:
We chose the high-quality T1 supporting font set Latin Modern by loading the
lmodern package
The last package we loaded is the blindtext. You don't need it in your final document;
here, it will serve us to provide filler text. Using such dummy text, we can get a better idea
of the final result before writing the actual content.
Finally, we switched to the so-called French spacing, which means that after ending a
sentence, we will get a normal interword space, not a wider space.
There's more...
You can change the layout of the book in many ways. Choose your settings at the beginning,
or even betterstart writing your content without any hesitationonce you have a decent
amount of text, you can better see the effects of layout changes. You can do this at any time.
Let's take a look at some design ideas.
20
Chapter 1
The actual text area has the same ratios as the page itself. This is automatically done by a
dividing construction, described in the KOMA-Script manual. It's really worth reading. You
can open it by typing the texdoc scrguien command in Command Prompt, or online at
http://texdoc.net/pkg/scrguien. The abbreviation, scrguien, comes from scr for
the original package name Script, gui for guide, and en for English, and, obviously, from the
ancient limit of eight characters per file name in older filesystems.
Besides the page and text area ratios, the result shows a bottom margin twice as high as
the top margin, and an outer margin with double the width of the inner margin. Imagine an
opened book, where the inner margins together appear with the same space as an outer
margin. Sometimes, people make the mistake of thinking that the inner margin should be
much bigger because of the binding, but that's done by raising the BCOR, as shown previously.
If you would like to get a bigger text area, which means narrower margins, you can still keep the
ratios as described. Just raise the division factor of the aforementioned internal construction
and check whether or not it would suit you. For example, set the class option as DIV=10; higher
values are possible. That's a safe and easy way to preserve sane layout proportions.
To sum up, our example with 5 mm binding loss and pretty narrow margins can start like this:
\documentclass[fontsize=11pt,paper=a5,pagesize=auto,
BCOR=5mm,DIV=12]{scrbook}
Alternatively, you can freely choose text and margin dimensions, when requirements of the
publisher or institute need to be met. This can be done by loading the classic geometry
package with the desired measurements, like we saw in the Writing a thesis recipe:
\usepackage[inner=1.5cm,outer=3cm,top=2cm,bottom=4cm,
bindingoffset=5mm]{geometry}
The \par command is equivalent to an empty line in the input. Sometimes, people use it to
keep the code compact, as we did here. We need to end the paragraph before the font size
changes because that size defines the space between lines. Hence, we ended the paragraph
before we closed the brace group. It's good to keep this in mind for when texts are longer.
Our only nontext design element is a modest horizontal line made by the \hrulefill line.
The preceding \noindent line just prevents an undesired paragraph indentation, so the line
really starts at the very left.
The \vfill line inserts stretching vertical space, so we get the last line pushed down to the
title page bottom.
We took this occasion to show some commands for positioning text on a page. You can
experiment with the \vspace and \vfill commands and their horizontal companions
\hspace and \hfill. Just avoid using such commands to fix local placement issues in the
actual document, when it would be better to adjust a class or package setting document wide.
Use these only in the final stage to make tweaks if any are required.
The titlepages package provides 40 example title pages in various
designs with full LaTeX source code. You can choose one, use it, and
customize it.
22
Chapter 1
The cover is different, for example, it should have symmetric margins, and it can be
designed according to your preference or individual choice. To get that deviating layout, it is
recommended that you use a separate document for it. Another reason is that it will usually
be printed on a different type of paper or cardboard.
So, you can start with an article-like class like the one we used in our first recipe, Writing
a short text. Use options such as twoside=false or the equivalent oneside option to
get symmetric margins. Then, you can proceed to positioning your text like we did with
the title page.
23
See also
A book may contain other elements, such as an index, a glossary, and a bibliography. Refer to
Chapter 7, Contents, Indexes, and Bibliographies, which contains such recipes.
Creating a presentation
At a conference or at a seminar, speakers often use a projector or a screen for presenting
written information in addition to what they are addressing. Such a presentation document
requires a specific kind of layout and features.
In our recipe, we will use the beamer class, which has been designed specifically for this
purpose. It provides the following features:
How to do it...
We will start off with a sample presentation document, which we can extend. Follow the given
steps:
1. Start with the beamer document class:
\documentclass{beamer}
4. Provide a title, subtitle, the names of the author and the institute, and a date:
\title{Talk on the Subject}
\subtitle{What this is about}
\author{Author Name}
\institute{University of X}
\date{June 24, 2015}
24
Chapter 1
5. Make a slide using the frame environment. The first one will contain the title page:
\begin{frame}
\titlepage
\end{frame}
6. Make a frame for the table of contents, with the title Outline. Add the option
pausesections, so the table of contents will be shown stepwise, section by section:
\begin{frame}{Outline}
\tableofcontents[pausesections]
\end{frame}
7.
8. All visible content goes into the frame environment, including lists, which are visually
better than normal text in a presentation:
\begin{frame}{Very Informative Title}
\begin{itemize}
\item First thing to say.
\item There is more.
\item Another short point.
\end{itemize}
\end{frame}
10. Add another subsection with a frame with a titled block. Also, add a new section
with a slide containing a list. We have highlighted some words by using the \alert
command. Finally, end the document:
\subsection{Another subsection}
\begin{frame}{Informative Title}
\begin{exampleblock}{An example}
An example within a block.
\end{exampleblock}
25
26
Chapter 1
How it works...
We loaded the beamer class and chose the theme with the name Warsaw. You can easily
replace it with another theme's name, compile it, and cycle through the themes until you find
the best one for your occasion. By default, the following themes are installed:
AnnArbor
Antibes
Bergen
Berkeley
Berlin
Boadilla
boxes
CambridgeUS
Copenhagen
Darmstadt
default
Dresden
EastLansing
Frankfurt
Goettingen
Hannover
27
Ilmenau
JuanLesPins
Luebeck
Madrid
Malmoe
Marburg
Montpellier
PaloAlto
Pittsburgh
Rochester
Singapore
Szeged
Warsaw
You can see these themes in the gallery at http://latex-beamer.net. We specified the
title, subtitle, author, and date of the seminar, which is then printed by \titlepage. We used
a frame environment, which we have to use for each slide.
The next frame contains the table of contents. We provided the frame title Outline as an
argument to the frame in curly braces. For the \tableofcontents command, we added the
pausesections option. As a result of doing this, section titles are printed one-by-one with a
pause in between. This gives us the opportunity to explain what the audience will hear before
they read further.
Here, we used the \section and \subsection commands just like in a normal LaTeX
document. The heading is not directly printed. The sections and subsections are printed in the
frame margin with the current position highlighted.
To get a bulleted list, we used an itemize environment just as we would in a normal
LaTeX document. The environments enumerate for numbered lists and description for
descriptive lists also work in the beamer frames.
To highlight information, we used the so-called block environments. Besides the standard
block environment, we can use the exampleblock and alertblock commands to get a
different style or color. The chosen theme determines the appearance of those blocks.
The \alert command is used to emphasize more distinctly, as seen in the last frame.
Now, you have the template and tools to create your presentation.
28
Chapter 1
Consider the following while designing a presentation:
There's more...
The beamer package has unique capabilities and an extraordinary design. We will explore
it in the following pages.
The same is possible for the \institute and \subtitle commands, if you would use
these commands in your presentation.
You can provide short names for sections and subsections in exactly the same way, so they
would better fit into their field within the frame margin; just use the optional argument in
square brackets. The \part and \subsubsection commands work similarly, they can
get a short name in square brackets as well.
29
Such a frame is then layered; that is, divided into overlays. They are internally numbered. If
you would like to show something at a certain overlay, you can tell the beamer package when
to uncover it:
\uncover<3->{Surprise!}
This shows your text on slide 3 of the current frame; and it will stay on the following slides
in that frame. Omit the dash for restricting it to only slide 3. You can also list multiple slides,
such as <3,5>, give ranges such as <3-5>, and mix the two, as in <3,5->.
This syntax works with overlay-specification-aware commands. Among them, there are \item,
\includegraphics, and even \renewcommand, so you can use them with an overlay
specification such as the following:
\includegraphics<3->{filename}
Overlays should not be too fancy. A presentation needs a linear structure; complicated
overlays may be handy for showing and hiding annotation to an object, while you explain that.
Refer to the beamer manual for more information on using overlays. You can open that manual
via texdoc beamer in Command Prompt, or online at http://texdoc.net/pkg/beamer.
30
Chapter 1
\includegraphics[width=3cm]{filename}
\end{column}
\end{columns}
\end{frame}
We started the multicolumn area using the column environment. You can specify alignment
options t, b, or c for top, bottom, or centered alignment of the column. Centered is the
default. While t aligns at the baseline of the first line, which is common in LaTeX, there's a
handy additional option, T, which aligns at the very top.
Each column is created by the column environment. The column width is given as an
argument. It understands the same positioning options, so you can override what you set in
the surrounding columns environment. We added the [T] option here, because an image has
its baseline at its bottom, and we want to change it to the very top.
You can also use the \AtBeginSection command to insert different lines of code.
If something should happen in case of a starred \section* too, you can insert the
corresponding code within an optional argument in square brackets after \AtBeginSection.
31
Another available font theme is professionalfonts, which actually doesn't change fonts,
but simply uses the set you specify separately. Furthermore, there are structurebold,
structureitalicserif, and structuresmallcapsserif, which change the font in the
structure, that is, in headlines, footlines, and sidebars, to such a shape combination.
There are outer color themes, providing a color set for headlines, footlines, and sidebars.
The author of the beamer package gave them sea animal names: dolphin, whale, and
seahorse. Then, there are inner color themes for elements, such as color blocks, with names
of flowers: lily, orchid, and rose. Combine inner and outer color themes as you like.
Finally, there are complete themes covering all structure aspects: albatross, beaver,
beetle, crane, dove, fly, monarca, seagull, spruce, and wolverine. They are named
after flying animals, except wolverine, beaver and spruce, which are external additions.
A lot of names, you may go through them using the \usecolortheme command to find the
color set you like the most.
Providing a handout
You can give your audience a printed version of the slides. Just create a version of your
document with the handout option, so no overlays will be used:
\documentclass[handout]{beamer}
32
Chapter 1
Slides are commonly small, so it's good to print several slides on a single page:
\usepackage{pgfpages}
\pgfpagesuselayout{4 on 1}[a4paper,
border shrink=5mm,landscape]
This prints four slides on an A4 page in landscape. You can get bigger prints, two slides on
each page, in portrait mode, by specifying the following line of code:
\pgfpagesuselayout{2 on 1}[a4paper,border shrink=5mm]
We used the pgfpages option, a utility package that comes with the pgf package.
See also
For the best quality with included graphics, refer to Chapter 4, Working with Images.
In Chapter 9, Creating Graphics, you can find recipes for quickly creating diagrams
and charts, which are good tools for visualizing data in a presentation.
Getting ready
If it's not already installed on your computer, download and install moderncv from CTAN
(http://ctan.org/tex-archive/macros/latex/contrib/moderncv).
If your TeX installation provides a package manager, use it for the installation.
There's a directory of examples, containing templates which you can use. Either locate
it in the documentation branch of your TeX directory tree, or visit the preceding CTAN link
for downloading.
33
How to do it...
We will start using a sample file provided by the moderncv package. Perform these steps:
1. Copy the file template.tex, into your document directory and rename it. Choose
any name you like. I named it as MyCV.tex.
2. Open that document, that is, MyCV.tex, and look around to understand the
template. Luckily, it is full of comments on how to use it. Compile it to ensure that this
document works.
3. Review and edit the class and package options in MyThesis.tex.
4. Remove the filler text and type in your own data. At the beginning, your document may
look like this:
\documentclass[11pt,a4paper,sans]{moderncv}
\moderncvstyle{classic}
\moderncvcolor{blue}
\usepackage[scale=0.75]{geometry}
\name{John}{Doe}
\title{CV title}
\address{street and number}{postcode city}{country}
\phone[mobile]{+1~(234)~567~890}
\phone[fixed]{+2~(345)~678~901}
\email{[email protected]}
\homepage{www.johndoe.com}
\photo[64pt][0.4pt]{ctanlion.pdf}
\begin{document}
\makecvtitle
\section{Education}
\cventry{year-year}{Degree}{Institution}{City}{\textit{Grade}}%
{Description}
\cventry{year-year}{Degree}{Institution}{City}{\textit{Grade}}%
{Description}
\section{Experience}
\subsection{Vocational}
\cventry{year--year}{Job title}{Employer}{City}{}%
{General description\newline{}Detailed achievements:%
\begin{itemize}%
\item Achievement 1;
34
Chapter 1
\item Achievement 2, with sub-achievements:
\begin{itemize}%
\item Sub-achievement (a)
\item Sub-achievement (b)
\end{itemize}
\item Achievement 3.
\end{itemize}}
\cventry{year--year}{Job title}{Employer}{City}{}
{Description line 1\newline{}Description line 2}
\subsection{Miscellaneous}
\cventry{year--year}{Job
title}{Employer}{City}{}{Description}
\section{Languages}
\cvitemwithcomment{Language 1}{Skill level}{Comment}
\cvitemwithcomment{Language 2}{Skill level}{Comment}
\end{document}
35
How it works...
We loaded the moderncv package. We used 11 pt as the base font size; 10 pt and 12 pt are
also supported. We selected A4 paper; other paper size options are a5paper, letterpaper,
legalpaper, and executivepaper. You can also add the landscape option. We chose a
sans serif font, which is fine for such lists; alternatively, you could write Roman alphabets for a
serif font.
We selected the classic style. Other available styles are casual, oldstyle, and banking.
Our color style is blue. Other color options are orange, green, red, purple, gray, and
black.
We loaded the geometry package with a scaling factor for reducing the margins.
Using macros such as the \name and \address, we entered our personal data.
The \photo command includes our photo; the size options are the height to which it is scaled
and the thickness of the frame around the photo. In this recipe, we used the CTAN lion drawn
by Duane Bibby for the photo.
The document body is divided into sections and subsections, just with a special design.
Then, the \cventry command makes a typical resume entry for job or education. Use it as
follows:
\cventry[spacing]{years}{job title}
{employer}{localization}{detail}{job description}
You can leave the last four arguments empty if you don't need them.
A simpler line is created using \cvitem, as follows:
\cvitem[optional spacing length{header}{text}
The \cvitemwithcomment command works in a similar way, just with another argument
that is printed at the right.
If you are looking for deeper information beyond this quick start guide, some more commands
and options are explained in the very well-documented template.tex file, as well as in the
class file moderncv.cls itself.
36
Chapter 1
See also
The template file contains a letter template that you can use for an application. Another
approach is explained in the next recipe.
Writing a letter
Letters have a specific structure. Commonly, they have an addressee field at a fixed position,
which should be visible in the envelope window. It also should show a back address, of yourself
as the sender. An opening text and a closing phrase are usual elements, and you may add fold
marks and enclosures.
How to do it...
We will use a KOMA-Script class, which has been specifically designed for letters, named
scrlttr2. Take a look at the following steps:
1. Use the scrlttr2 class, activate the address field and fold marks using the options
as follows, and align the sender's address to the right:
\documentclass[addrfield=true,foldmarks=true,
fromalign=right]{scrlttr2}
2. Provide your name and your address using the \setkomavar command:
\setkomavar{fromname}{Thomas Smith}
\setkomavar{fromaddress}{123 Blvd \\ City, CC 12345}
7.
37
That was pretty easy! You got a fully fledged formal letter with addressing information, an
envelope window support, date of writing, phrases, signature, and even fold marks.
Now you can enter the real addresses and the actual letter text.
How it works...
When loading the letter class scrlttr2, we activated the address field, switched on fold
marks, and set the options for aligning the sender's address to the right.
The scrlttr2 class is quite different from other classes, so it has a special interface.
Using the \setkomavar command, we set the content of class variables, similar to the
\renewcommand command. Here, we set the name and address. The KOMA-Script manual
explains all the available variables. As mentioned in the recipe Writing a book, you can open
it by typing the texdoc scrguien command in Command Prompt, or online at http://
texdoc.net/pkg/scrguien.
38
Chapter 1
We used a letter environment for the actual content, including the opening and closing
phrases. The address is a mandatory argument for that environment. You can have several
letter environments in a single document.
There's more...
For improving input and hyphenation, and for changing the font, take a look at the first recipe
in Chapter 2, Tuning the Text.
Let's take a look at some letter specific options.
Separating paragraphs
Instead of indenting the beginnings of paragraphs, you can indicate a paragraph break with
an empty line instead. For this, simply add the following option to the comma-separated list
of class options at the beginning:
parskip=full
It would be indented. You can get it left-aligned by specifying the following code:
\renewcommand{\raggedsignature}{\raggedright}
Adding enclosures
If you wish to add enclosures to your letter, it's a common practice to mention them. You can
do this by inserting an \encl command right before the \end{letter} command:
\encl{Curriculum vitae, certificates}
You can change the default encl: if you like by modifying the corresponding variable before
calling the \encl option:
\setkomavar*{enclseparator}{Attached}
We used the starred version, \setkomavar*, which modifies the description of a variable
instead of its content, which actually is :, that is, a colon followed by a space.
39
Producing a leaflet
Flyers are a common way to promote an event or to inform about a product. In particular, a
folded leaflet is very handy as a giveaway and to carry around, so let's see how to produce one.
How to do it...
The intended layout is very different compared to the already shown document types.
Fortunately, there's a document class for it with the name leaflet, which we will use now.
Let's start filling it with some content. Let's take a look at the following steps:
1. Start with the leaflet document class. Choose a base font size of 10 pt, and set
the option notumble, which keeps the back side printed in the same direction:
\documentclass[10pt,notumble]{leaflet}
3. If you want a nondefault font, load it, this time we chose the Linux Libertine font:
\usepackage{libertine}
7.
9. Set the title, author's name, and date. Then, print the title:
\title{\textbf{\TeX\ Live Install Party}}
\author{\Large\textbf{Your \TeX\ team}}
\date{\textbf{August 11, City Hall Cellar}}
\maketitle
40
Chapter 1
10. Include a centered image. Here, we chose the CTAN lion:
\begin{center}
\includegraphics[width=\linewidth]{ctanlion.pdf}
\end{center}
12. A bulleted list can be a good idea for a catchy text. Use an itemize environment for
it, each list item starting with \item:
\begin{itemize}
\item a fast internet connection fow downloading,
\item media such as DVDs and USB sticks with
the latest \TeX\,
\item \TeX\ books for bying with a discount,
\item chat with \TeX\ experts.
\end{itemize}
13. End the page. Fill in more text on the next page of the leaflet, which will be printed on
the back side of the paper, next to each other:
\clearpage
Fill in text for page 2 (on the back side)
\clearpage
Fill in text for page 3 (on the back side)
\clearpage
Fill in text for page 4 (on the back side)
\clearpage
14. Now, pages 5 and 6 of the leaflet come to the front side of the paper. Use the
\section command to insert a heading:
\section{Schedule}
15. You can add a timetable using a tabular environment. Using the @{} option, we
suppress spacing at the left and right:
\begin{tabular}{@{}rl@{}}
6 pm
& Welcome \\
41
16. End the paragraph with an empty line, continue writing the text, and finally end the
document:
From 6pm to 10pm: install support and free \TeX\ copies on DVD on
our welcome desk.
\section{Accomodation}
Hotel, Meals, Travel information here
\section{Sponsors}
Information about our local \TeX\ user group
and Open Source projects sponsor
\clearpage
\section{Contact}
Names, Phone numbers, email addresses
\end{document}
42
Chapter 1
The back side still contains just some dummy text, which helps to identify the position where
the text finally lands on the page.
How it works...
In the first line, we loaded the leaflet package with a font size of 10 pt. The notumble
option suppresses the default behavior, that is, printing the back side upside down.
The next three lines contain our font settings. We used the Linux Libertine font and specified
the T1 font encoding. You can read more about encodings in Chapter 2, Tuning the Text,
specifically in the Improving justification and hyphenation recipe. Furthermore, we set the
default font family to be sans serif. I prefer the clean look of sans serif on a flyer or a leaflet,
which usually contains little text.
The remaining part of the preamble is as follows:
We loaded the microtype package, which improves the justification capabilities with
tiny font adjustments. This is especially useful in a situation with narrow columns,
such as in this case.
We loaded the graphicx package, so we are able to include images such as a logo
or a geographic map.
We hid the page numbers. The \gobble command is a TeX command that removes
the following command or control sequence, so the page number will simply be
absorbed.
Our document body shows usual sectioning commands and text. You can see that we added
an explicit space after the TeX logo by inserting a backslash and a following space. That's
because the space after a macro, such as the \TeX command, just indicates the end of the
macro. It doesn't produce a space in print because punctuation may follow the macro.
To have an image in our template, we used the CTAN lion drawn by Duane Bibby; simply
replace it with your own image, for example, a geographic map or logo.
The remaining text is straightforward and shows some useful layout details, as follows:
43
There's more...
The leaflet class provides some options and commands for customization.
You can draw a vertically dotted line with a scissors symbol using the \CutLine command in
the preamble with a page number as an argument. The line will go between this one and the
preceding page, which is as follows:
\CutLine{3}
This will print a dotted line with two scissors symbols on the back side, between pages 2 and
3, where a folding mark will be placed by default. The starred command version \CutLine*
will not print the scissors.
44
Chapter 1
This will give a large sans serif font in bold and with blue color.
For further information regarding fonts, refer to Chapter 3, Adjusting Fonts.
People may look at them from far away, but also from a very short distance
The page layout dimensions should work with such a big size.
We need a wide range of font sizes. We should be able to read while standing close,
but we also need large, catchy headings.
The poster should be partitioned into digestible blocks. Specifically, each block
should not exceed the usual line width we know from body texts. Also, excessively
wide lines will make it hard to focus and to skip back to the start of the next line. So,
the lines in blocks should not be much wider than about 40 or 50 characters long.
Graphical elements such as colors and lines can be used to divide the poster
contents in parts.
In this recipe, we will create a poster of A0 size in landscape orientation. It will show some
blocks containing the dummy text as a placeholder, math, and images. As sample images, we
will take a flowchart from Chapter 9, Creating Graphics, and a plot from Chapter 10, Advanced
Mathematics. There, you can find the source code. You can later replace the dummy text and
other parts with your own content.
45
How to do it...
We will use the tikzposter class. The document is structured in columns and blocks. Follow
these steps:
1. Begin with the document class. A0 is the default paper size. We state landscape
orientation as the option:
\documentclass[landscape]{tikzposter}
2. Choose a theme, which provides a set of colors and decorations. We choose the blue
Wave theme:
\usetheme{Wave}
4. For dividing wider blocks in text columns, we load the multicol package. On
account of the large paper, we set the column separation and the separation
line width to high values:
\usepackage{multicol}
\setlength{\columnsep}{4cm}
\setlength{\columnseprule}{1mm}
5. Define macros for repeated tasks, if desired. In our case, it will be a macro for
including an image with an optional caption:
\newcommand*{\image}[2][]{%
\begin{tikzfigure}[#1]
\includegraphics[width=\linewidth]{#2}
\end{tikzfigure}}
7.
46
Chapter 1
9. Start a column with a width of 65 percent of the available text width:
\column{.65}
10. Define a block with the title Workflow in the first argument; the second argument
containing dummy text and an image:
\block{Workflow}{
\lipsum[1]
\image[\LaTeX\ workflow]{flowchart}
}
12. The first subcolumn will take half of the available width, in this case, the width of the
left column:
\subcolumn{.5}
13. Create a block with a bulleted list and a mathematical equation to get a feeling of
how it will look on a poster. We will also use a colored box and an inner block with a
title for the equation:
\block{Mathematics}{
Take a coffee, then:
\bigskip
\coloredbox{\begin{itemize}
\item State
\item Proof
\item Write in \LaTeX
\end{itemize}}
\bigskip
\innerblock{Integral approximation}{
\[
\int_a^b f(x) dx \approx (b-a)
\sum_{i=0}^n w_i f(x_i)
\]
}
}
47
15. Make another subcolumn, taking the other half of the available width. Insert a block
filled with text and end the subcolumns environment:
\subcolumn{.5}
\block{Text}{\lipsum[1]}
\end{subcolumns}
16. Now that we are back to our main column environment, make another column, print
a block with an image and some text, and then end the columns environment:
\column{.35}
\block{Plotting functions}{
\image{plot}
\lipsum[4]
}
\end{columns}
17. As we ended the columns, a block will use the whole available width. To keep the
text readable, we will now use the multicol package. We divide the text itself into
columns using a multicolumn environment with four columns:
\block{Conclusion and outlook}{
\begin{multicols}{4}
\lipsum[10-11]
\end{multicols}
}
48
Chapter 1
19. Compile the document, and take a look:
How it works...
The tikzposter package supports large paper sizes, large fonts, and it takes care of block
heights and spacing between columns. We, as users, just decided the relative column width.
Several class options are provided. You can add them to the \documentclass command like
we did with the preceding landscape option. Let's take a look at the following:
The paper size can be chosen with the a0paper, a1paper, or a2paper options. The
a0paper option is the default.
The available font sizes are 12pt, 14pt, 17pt, 20pt, and 25pt. The last one is the
default.
You can select the orientation by using the landscape or portrait command. The
portrait option is the default.
The standard option leqno for numbering the equation at the left-hand side is also
supported.
49
margin: This is the distance between the edge of the poster area and the edge of
the paper
innermargin: This is the distance from the outermost edge of the blocks to the
edge of the poster
blockverticalspace: This is the distance between the bottom of a block and the
The tikzposter package makes use of the very capable graphics language TikZ. We
will see more of TikZ in Chapter 9, Creating Graphics. For now, the main benefit is that
tikzposter provides a lot of predefined styles and color schemes.
You can use a main layout style by using the \usetheme{name} command. When this book
came out, there were nine themes available:
Default (left) and Basic (right): This is shown in the following image:
50
Chapter 1
51
There's more...
One of the first poster classes is a0poster. It actually supports the paper sizes A0, A1, A2,
and A3. It provides font sizes from 12 pt up to 107 pt. Math formulas are printed in a suitable
size. There's no specific support for graphics, color, or text placement. For this, you would
need additional packages, such as TikZ.
In the recipe Creating a presentation, you saw the beamer package as a presentation class.
The beamerposter package can be used together with it to produce presentations in poster
size. It combines the beamer package with the a0poster code. So, you can produce large
posters with a wide range of font sizes together with the beamer package's color and graphics
capabilities, such as the beamer boxes with titles.
As mentioned previously, you can use the texdoc command or the Internet site http://
texdoc.net to access the documentation of the aforementioned classes and packages.
Another solution is provided by the baposter template. It provides blocks with headings
and positioning support. Furthermore, it offers a set of predefined styles. Its download and
documentation are available at http://www.brian-amberg.de/uni/poster/.
52
www.PacktPub.com
Stay Connected: