Skip to content
ImagineWorld

Using Hyperlinks and Designing Headings

node_idnode-book_latex-beginner-s-guide_chapter-12-using-hyperlinks-and-designing-headings
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num12
chapter_titleUsing Hyperlinks and Designing Headings
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 12 — Using Hyperlinks and Designing Headings

Section titled “Chapter 12 — Using Hyperlinks and Designing Headings”

In the previous chapter, you learned how to structure and manage large documents. With all that you learned up to this point, you can produce well-structured documents with fine typographical quality, suitable for books, journal articles, or a university thesis.

If you plan to publish your work online, your PDF document would benefit from features such as hyperlinks and bookmarks that support navigation.

In this chapter, we will work with tools for such navigation enhancements and for customizing headings and colors in the following sections:

  • Working with hyperlinks
  • Creating bookmarks
  • Designing headings

Each topic is handled with dedicated LaTeX packages, which we will now explore.

There’s a sophisticated package called hyperref that automatically adds hyperlinking features to nearly every structural element of a LaTeX document. Let’s see how it works.

Load the hyperref package and inspect the result:

  1. Open the preamble.tex file, which we used in the previous chapter. At the end, add this line:
    \usepackage{hyperref}
  2. Save this document under the same name.
  3. Open our Book of Equations from the previous chapter; we called it equations.tex.
  4. Compile the document twice without making any changes. Let’s see how the document now appears; here, we can see red boxes indicating hyperlinks:

Figure 12.1 – A table of contents with hyperlinks and bookmarks

Figure 12.1 – A table of contents with hyperlinks and bookmarks

Cross-references, such as references to equation numbers, also have red boxes:

Figure 12.2 – References to equations with hyperlinks

Figure 12.2 – References to equations with hyperlinks

By just loading the hyperref package, our document has significantly changed:

  • We got a Bookmarks bar that allows us to navigate the document easily
  • The document contains hyperlinks that are highlighted by red borders
  • Each entry in the table of contents has become a hyperlink to the beginning of the corresponding chapter
  • All cross-references have become hyperlinks

This is an excellent improvement for electronic versions of our documents.

The red boxes will not appear on paper when you print the document; they appear only on screen for electronic navigation. The same applies to the bookmarks.

If you don’t like the default red border for hyperlinks, you can easily change it by editing the hyperref options. Let’s try this next.

Now, we’ll pass options to the hyperref package that modify the way links are emphasized:

  1. Open the preamble.tex file again. This time, specify the options for hyperref:
    \usepackage[colorlinks=true,linkcolor=red]{hyperref}
  2. Save this document, go to the main equations.tex document, and compile it twice. The table of contents has changed:

Figure 12.3 – Table of contents with colored hyperlinks

Figure 12.3 – Table of contents with colored hyperlinks

Instead of frames, we now use red for emphasized hyperlinks. Unlike the boxes, we can see the color in a printed document.

hyperref provides ways to configure these options. The first one we used is the following:

\usepackage[key=value list]{hyperref}

Alternatively, we could write \usepackage{hyperref} and set the options afterward:

\hypersetup{key=value list}

Our example would do the same with the following:

\hypersetup{colorlinks=true,linkcolor=red}

We can also combine these methods.

Let’s look at a selection of handy options. For the following options, choose true or false. If you don’t specify a value, hyperref selects the default one, which is shown in parentheses here:

  • draft: Turns all hypertext options off (false)
  • final: Turns all hypertext options on (true)
  • debug: Prints extra diagnostic messages into the log file (false)
  • backref: Adds backlinks to the bibliography, that is, links from bibliography items back to citations in the text (false)
  • hyperindex: Adds links to page numbers in the index (true)
  • hyperfootnotes: Converts footnote markers into hyperlinks (true)
  • hyperfigures: Adds hyperlinks to figures (false)
  • linktocpage: Adds links to page numbers instead of to the text in the table of contents (TOC), list of figures (LOF), and list of tables (LOT) (false)
  • frenchlinks: Uses small caps for links instead of color (false)
  • bookmarks: Writes bookmarks for the PDF reader navigation (true)
  • bookmarksopen: Shows all bookmarks in an expanded view when the PDF is opened (false)
  • bookmarksnumbered: Includes the section number in bookmarks (false)
  • colorlinks: Writes links and anchors in color, depending on the type of link, such as page references, URLs, file references, and citations, instead of printing a border around links (false)

When you enable the colorlinks option, you can choose the color for each link type from the following list. Again, the default value is in parentheses:

  • linkcolor: Color of general links (red)
  • citecolor: Color for citations of bibliography items (green)
  • urlcolor: Color for website addresses, that is, URLs (magenta)
  • filecolor: Color for links to files (cyan)

There are many more options for customizing link borders, the PDF page size, anchors, bookmark appearance, and the PDF page display style. The hyperref documentation lists them all. Just type texdoc hyperref at the command line or visit https://texdoc.org/pkg/hyperref.

Suppose you want to turn off all link highlighting, such as for printing on paper; give the hidelinks option without a value. Then, links will appear as regular text without borders or colors.

Some text options allow us to specify the metadata of PDF files, such as the author’s name, title, and keywords. You can see this information by inspecting the document properties in the PDF reader. This is even more beneficial, as internet search engines can find and classify your PDF document based on this metadata. If you publish online, this improves the chances of readers finding your publication.

That’s why we will now add PDF metadata to our Book of Equations from Chapter 11, Developing Large Documents. In addition to choosing sensible keywords, we will set the title and the author’s name. During development, why not choose the great mathematician to whom we dedicated our book? Let’s do it:

  1. Open the preamble.tex file and add the following lines:
    \hypersetup{pdfauthor={Carl Friedrich Gauss},
    pdftitle={The Big Book of Equations},
    pdfsubject={Solving Equations and Equation Systems},
    pdfkeywords={equations,mathematics}}
  2. Save that file. Go to the main equations.tex document and click Typeset to compile.
  3. Let’s inspect the Document Properties section. If you are using Acrobat Reader, click on the File menu and then on Properties:

Figure 12.4 – PDF metadata in Document Properties

Figure 12.4 – PDF metadata in Document Properties

That was easy. We provided all the document properties using hyperref options; we just had to enclose each entry in curly braces.

The most used metadata options are the following:

  • pdftitle
  • pdfauthor
  • pdfsubject
  • pdfcreator
  • pdfproducer
  • pdfkeywords

PDF metadata stores basic information about a document for readers and search engines. The most common metadata fields describe the document itself: pdftitle, pdfauthor, and pdfsubject define the title, author, and overall topic, respectively. The pdfcreator and pdfproducer fields document the software used to generate and process the PDF, which is usually set automatically but can be customized. Carefully choosing metadata is worthwhile, especially for PDFs shared online. Use a clear, descriptive title instead of a filename, and pick a small, focused set of meaningful keywords. Think about what readers might search for, and avoid vague terms. Good metadata improves searchability and gives your PDF a more professional finish.

Because the hyperref package redefines many other packages’ commands to add hyperlink functionality, we must load it after those packages. A good rule of thumb is to load the hyperref package last in your preamble. A few packages are exceptions to that rule, namely, algorithm, amsrefs, bookmark, chappg, cleveref, glossaries, hypernat, linguex, sidecap, and tabularx. For more information, see https://latexguide.org/hyperref.

There are further ways to add hyperlinks and bookmarks, which we will see now.

Since the hyperref package automatically creates links for nearly all kinds of cross-references, you seldom need to create hyperlinks yourself. Still, the package provides user commands for doing so when needed:

  • \href{URL}{text} turns text into a hyperlink that points to the URL (the website address)
  • \url{URL} prints the URL and links it
  • \nolinkurl{URL} prints the URL without linking it
  • \hyperref{label}{text} converts the text into a hyperlink that links to the location where the label is set (i.e., the same place \ref{label} would point to)
  • \hypertarget{name}{text} creates a target name for potential hyperlinks with text as the anchor
  • \hyperlink{name}{text} turns text into a hyperlink that points to the target name

An anchor is an internal jump target in the document. Sectioning commands such as \chapter or \section automatically create anchors, which hyperlinks and TOC entries can point to.

Sometimes, however, you add an entry to the TOC manually using the \addcontentsline command, which creates a hyperlinked TOC entry. Still, there hasn’t been a corresponding sectioning command setting the anchor. The TOC entry points to the most recently created anchor, which may be the previous chapter or section. As a result, clicking the TOC entry jumps to the wrong page.

The \phantomsection command comes to the rescue; it just sets an anchor like \hypertarget{}{} would do. It’s often used this way for creating a TOC entry for the bibliography while linking to the correct page, as follows:

\cleardoublepage
\phantomsection
\addcontentsline{toc}{chapter}{Bibliography}
\bibliography{name}

In effect, you can think of \phantomsection as inserting an invisible \section anchor. The following \addcontentsline command then refers to that anchor.

Your Bookmarks panel might already be full of chapters and section entries created by hyperref. But what if you want to add bookmarks by yourself? You can do that as follows.

\pdfbookmark[level]{text}{name} creates a bookmark with text at the optionally specified level. The default level is 0. Treat the name just like with the \label command; it should be unique because it identifies the internal anchor.

You can also insert bookmarks relative to the current level:

  • \currentpdfbookmark{text}{name} places a bookmark at the current level
  • \belowpdfbookmark{text}{name} creates a bookmark one level deeper
  • \subpdfbookmark{text}{name} steps down one level and creates a bookmark at that deeper level

The bookmark package offers additional customization options, including font style and color. You can read about it by running texdoc bookmark at the command line or visiting https://texdoc.org/pkg/bookmark.

Using math formulas and special symbols in bookmarks

Section titled “Using math formulas and special symbols in bookmarks”

Due to PDF limitations, we cannot use math and special symbols within PDF bookmarks. This becomes an issue, for instance, when a sectioning title contains math symbols or font commands, as hyperref would try to place them into the bookmark. To avoid this, you can provide two versions of the title: one for TeX and one for the PDF bookmark. Use this command:

\texorpdfstring{string with TeX code}{pdf text string}

It returns the argument depending on the context to avoid such problems. It can be used like this:

\section{The equation
\texorpdfstring{$y=x^2$}{y=x\texttwosuperior}}

That may come in handy.

If you load hyperref with the unicode option, you could use Unicode text characters in bookmarks, such as here:

\section{\texorpdfstring{$\gamma$}{\textgamma} radiation}

Let’s quickly see how these commands work in a small sample document. Here it goes:

\documentclass{article}
\usepackage{bm}
\usepackage[colorlinks=true,psdextra,unicode]{hyperref}
\begin{document}
\pdfbookmark[1]{\contentsname}{toc}
\tableofcontents
\pdfbookmark[1]{Abstract}{abstract}
\begin{abstract}
\centering
Sample sections follow.
\end{abstract}
\section{The equation
\texorpdfstring{$y=x^2$}{y=x\texttwosuperior}}
\section{\texorpdfstring{$\gamma$}{\textgamma} radiation}
\section[\texorpdfstring{Let $\int\sim\sum$ for
$n\rightarrow\infty$}
{Let \int\sim\sum\ for n\rightarrow\infty}]
{Let $\bm{\int\sim\sum}$ for $\bm{n\rightarrow\infty}$}
\end{document}

As highlighted in the preceding code, the \section command does these three things:

  • It prints the section heading. This time, we used the \bm command from the bm package to produce bold math. Compare it with the other headings.
  • It puts the section name into the TOC.
  • It creates a bookmark with Unicode text symbols in place of math symbols. We loaded hyperref with the unicode and psdextra options, which allow math symbols in bookmarks.

We get this output with bookmarks:

Figure 12.5 – Math formulas in bookmarks

Figure 12.5 – Math formulas in bookmarks

In the first argument to the \texorpdfstring command, we used $…$ to enter the math mode. However, in the second argument to \texorpdfstring, we omitted $…$ intentionally since that will be Unicode text, not math font glyphs.

While math formulas in headings and bookmarks may not be a good idea anyway, we can do it if we really need to.

In the next section, we will turn to the design and formatting of headings.

In Chapter 2, Formatting Text and Creating Macros, we briefly touched on the challenge of customizing headings. There has to be a consistent way to modify the font, spacing, and numbering of headings throughout the document. Fortunately, there’s a handy package for that: titlesec. We’ll use it now to design chapter and section headings.

Let’s return to the example that we used earlier in this chapter. We aim to create headings with the following characteristics:

  • Centered titles
  • A smaller font size
  • Reduced space above and below
  • A sans-serif font, which is a good choice for bold headings

Let’s start:

  1. Open the preamble.tex file, which we used earlier in this chapter. Insert this line to load the titlesec package:
    \usepackage{titlesec}
  2. Add this command to specify the layout and font of the chapter headings:
    \titleformat{\chapter}[display]
    {\normalfont\sffamily\Large\bfseries\centering}
    {\chaptertitlename\ \thechapter}{0pt}{\Huge}
  3. Now, define the section heading by calling the \titleformat command again:
    \titleformat{\section}
    {\normalfont\sffamily\large\bfseries\centering}
    {\thesection}{1em}{}
  4. Add this line to adjust the chapter heading’s spacing:
    \titlespacing*{\chapter}{0pt}{30pt}{20pt}
  5. Save preamble.tex and compile the main equation.tex document. Let’s see how the headings have changed:

Figure 12.6 – Centered headings

Figure 12.6 – Centered headings

In step 1, we loaded the titlesec package, which provides a comprehensive interface for customizing headings of parts, chapters, sections, and even smaller sectioning parts down to subparagraphs.

In step 2, we selected a display style that places the heading number and the title on separate lines. We first switched to the base font using the \normalfont command, to be on the safe side. By applying \sffamily, we switched to a sans-serif font, set the size and weight, and finally, declared that the entire heading shall be centered.

In step 3, everything is very similar to step 2; we just omitted [display] to get the number and title on the same line.

To understand the remaining arguments, have a look at the general form of the \titleformat command:

\titleformat{cmd}[shape]{format}{label}{sep}{before}[after]

The meaning of the arguments is as follows:

  • cmd stands for the sectioning command that we redefine, that is, \part, \chapter, \section, \subsection, \subsubsection, \paragraph, or \subparagraph.
  • shape specifies the paragraph shape, with the effect of the possible values as follows:
    • display puts the label into a separate paragraph
      • hang creates a hanging label, like in standard sections, and is the default option
      • runin produces a run-in title like \paragraph does by default
      • leftmargin sets the title into the left margin
      • rightmargin puts the title into the right margin
      • drop wraps the text around the title, and requires care to avoid overlapping
      • wrap works like drop, but adjusts the space for the title to match the longest text line
      • frame works like display and additionally frames the title
  • format may contain commands that will be applied to the label and text of the title.
  • label prints the label, that is, the number.
  • sep is a length that specifies the separation between the label and title text. With the display option, it’s the vertical separation. With the frame option, it means the distance between the text and the frame. Otherwise, it’s the horizontal separation between the label and title.
  • before can contain code that comes before the title body. The last command is allowed to take an argument, which should then be the title text.
  • after can contain code that comes after the title body.

That’s a lot of options. Have a look at the titlesec documentation to learn even more by running texdoc titlesec or visiting https://texdoc.org/pkg/titlesec.

We used the titlesec command called \chaptertitlename, which defaults to \chaptername. So, it defaults to Chapter. In an appendix, it changes to \appendixname.

Using the following command, we customized the spacing of all chapter headings:

\titlespacing*{cmd}{left}{beforesep}{aftersep}[right]

The arguments have the following meanings:

  • left works differently depending on the chosen shape: with drop, leftmargin, and rightmargin, it’s the title width. With wrap, it’s the maximum width. With runin, it sets the indentation before the title. Otherwise, it increases the left margin. If negative, it decreases, meaning it overhangs into the margin.
  • beforesep sets the vertical space before the title.
  • aftersep sets the separation between the title and text. With a hang, block, and display shape, it has a vertical meaning. With a runin, drop, wrap, leftmargin, and rightmargin shape, it’s a horizontal width. Again, it may be a negative value.
  • right increases the right margin when a hang, block, or display shape is used.

If you use the star, titlesec removes the indentation of the following paragraph. That’s like standard sections: the text that follows a section heading doesn’t have paragraph indentation. With drop, wrap, and runin, the starred version has no meaning.

In our example, we avoided indenting the paragraph following a chapter heading and specified a 30pt space before the heading and a 20pt space after it. That’s less compared to standard classes, which use 50pt above chapter headings.

It’s highly recommended to read the titlesec documentation to get the most out of it. Its appendix shows how the headings in standard classes would be defined using \titleformat and \titlesec. That’s a great way to start: copy these definitions and modify them.

Using sans-serif headings is very common today. They don’t have the heavy, ancient appearance of bold serif headings. However, serif text offers the best readability for body text. Now, it’s up to you to choose – you’ve got the tools.

In this chapter, we enhanced our document with a hypertext structure including colored links and bookmarks for navigation. We can now edit the PDF metadata and customize the styles of our headings.

In the next chapter, we will explore new ways of styles and navigation.