Tx · LaTeX & TikZ

How to Use Commands in PyLaTeX

Published By the 9to5Science editorial team

At a glance

  1. 1. Create a document

    Instantiate a PyLaTeX Document and add content to its body.

  2. 2. Add a command

    Use Command to represent a LaTeX command and its arguments.

  3. 3. Define custom commands

    Put a raw newcommand declaration in the document preamble.

  4. 4. Generate the file

    Generate a .tex file, then compile it with an installed LaTeX engine.

PyLaTeX lets you build LaTeX documents from Python objects. Its Command class represents a command you want in the output, such as \textbf{important}. A custom macro is different: it should usually be defined in the preamble before you use it in the document body.

The example below defines a \highlight macro and uses it in a generated document. It also shows how to add a built-in LaTeX command with PyLaTeX’s Command class.

Add a LaTeX command with Command

Pass the command name without the leading backslash. Supply its required argument with arguments:

from pylatex import Command, Document

doc = Document()
doc.append(Command('textbf', arguments='Important text'))

This adds the equivalent of \textbf{Important text} to the document body. A string argument is ordinary text, so PyLaTeX applies its usual escaping where needed. Use NoEscape only when the argument itself contains LaTeX syntax that should remain active.

Commands with optional arguments can be represented with the options parameter. For example, LaTeX’s \section command accepts an optional short title followed by a required title:

from pylatex import Command, Document

doc = Document()
doc.append(Command('section', options='Short title', arguments='Long title'))

This corresponds to \section[Short title]{Long title} in the generated text. Check the LaTeX command’s actual argument order before using options.

Define and use a custom macro

For a macro that should be available throughout the document, put its declaration in the preamble, the part of a LaTeX file before \begin{document}. PyLaTeX’s NoEscape wrapper preserves the backslashes and braces in a raw LaTeX declaration.

from pylatex import Command, Document, NoEscape, Section

doc = Document()

doc.preamble.append(
    NoEscape(r'\newcommand{\highlight}[1]{\textbf{#1}}')
)

doc.append(Command('title', 'A PyLaTeX example'))
doc.append(Command('maketitle'))

with doc.create(Section('Using a custom command')):
    doc.append('This word is ')
    doc.append(NoEscape(r'\highlight{highlighted}'))
    doc.append('.')

doc.generate_tex('pylatex_command_example')

The declaration \newcommand{\highlight}[1]{\textbf{#1}} defines a command named \highlight with one argument. The #1 in the definition stands for the text supplied when the macro is used. The body uses NoEscape because \highlight{highlighted} must be emitted as LaTeX markup rather than treated as literal text.

Running the script writes pylatex_command_example.tex. Compile that file with a LaTeX engine, such as pdflatex, to produce a PDF. PyLaTeX can also request PDF generation with doc.generate_pdf(...), but a working LaTeX installation is still required.

When to use Command and when to use NoEscape

Use Command for a command with a name and arguments that PyLaTeX can represent cleanly. It handles the command structure and helps distinguish ordinary text arguments from LaTeX syntax. Use NoEscape for a short raw fragment of LaTeX, including a macro declaration or a macro invocation that you want inserted exactly as written.

These approaches can be combined: use Command for routine document commands and raw NoEscape only for the pieces that need custom LaTeX syntax. That keeps the Python code readable without asking PyLaTeX to interpret a macro definition as ordinary prose.

Common mistakes

  • Defining a macro after its first use: \newcommand must appear before the macro’s first use. Put the definition in doc.preamble if it should be available throughout the document.
  • Forgetting NoEscape: a plain string containing LaTeX syntax may be escaped or treated as text. Wrap raw LaTeX in NoEscape.
  • Including the backslash in the Command name: write Command('textbf', ...), not Command(r'\textbf', ...).
  • Using a macro before defining it: LaTeX must encounter the \newcommand declaration before the macro’s first use.
  • Passing the wrong kind of arguments: options represents square-bracket options; arguments represents required arguments. Match these to the command’s actual LaTeX syntax.
  • Assuming generating .tex also creates a PDF: generate_tex writes source only. PDF generation requires a LaTeX engine and any packages your document uses.

References

  1. PyLaTeX documentation

Spotted an error? Send a correction. Read how we write and check articles in our editorial policy.