A Collection of Issues about the LaTeX Output in Sphinx and the Solutions

Sphinx is a powerful documentation generation tool, as well as a powerful book writing tool. It can generate multiple output formats, including LaTeX for printable PDF versions. However, the LaTeX output is often more problematic than the html output. In this post, a collection of common issues and their solutions are listed.

In this post, “adding something to the LaTeX preamble” means adding the contents to the preamble key of the latex_elements in conf.py. Please refer the relevant Sphinx documentation for details. For example, adding usepackage{example} to the LaTeX preamble means adding the following code to the latex_elements block in conf.py (Note the r before '''):

latex_elements = {
# other options
# ...
'preamble': r'''
% Whatever already here
% ...
% now comes the new code
\usepackage{example}
'''

The Output PDF Contains Too Many Blank Pages

This is because Sphinx generates a default conf.py with a double sided document class (manual). The issue can be resolved by change to a different document class such as report in the latex_documents option in conf.py, OR adding the following options to the latex_elements option in conf.py:

# No blank pages
'classoptions': ',openany',
'babel': r'\usepackage[english]{babel}',

If the page numbers do not show up correctly, add the following to your LaTeX preamble:

\pagestyle{plain}

Reference

Adding Math Equations to Section Titles Leads to Error

NOTE: this should be no longer an issue since Sphinx version 1.3.4

Example error message: LaTeX Error: Bad math environment delimiter.

The reason is that Sphinx uses ( and ) for equations, which causes problem when the table of contents needs to include these symbols. To solve this issue, adding the following to the LaTeX preamble:

\usepackage{etoolbox}
\robustify\(
\robustify\)

Reference

Using Some Directives Such as References in Figure Captions Leads to Error

NOTE: this should be no longer an issue since Sphinx version 1.3.4

Example error message: Incomplete iffalse; all text was ignored after line xxx.

This is caused by the use of phantomsection in figure environment, which is illegal. To solve this problem, add the following to the LaTeX preamble:

% make phantomsection empty inside figure environment
\usepackage{etoolbox}
\AtBeginEnvironment{figure}{\renewcommand{\phantomsection}{}}

Footnotes Numbering Does Not Reset on Every Page

Add the following to the LaTeX preamble:

\usepackage{perpage}
\MakePerPage{footnote}

I Want My Book to Start From “Chapter 0”

Add the following to the LaTeX preamble:

\setcounter{chapter}{-1}

Leave a Reply

Your email address will not be published.