or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

base-classes.mdconfiguration.mddocument.mdfigures.mdindex.mdlayout.mdlists.mdmath.mdquantities.mdreferences.mdsectioning.mdtables.mdtext-formatting.mdtikz.mdutilities.md
tile.json

tessl/pypi-pylatex

A comprehensive Python library for programmatically creating and compiling LaTeX documents and snippets.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/pylatex@1.4.x

To install, run

npx @tessl/cli install tessl/pypi-pylatex@1.4.0

index.mddocs/

PyLaTeX

A comprehensive Python library designed to programmatically create and compile LaTeX documents and snippets. PyLaTeX provides an intuitive, object-oriented interface that bridges Python programming with LaTeX document generation, allowing developers to build complex documents, reports, and presentations through code.

Package Information

  • Package Name: PyLaTeX
  • Language: Python
  • Installation: pip install PyLaTeX

Core Imports

import pylatex

Common imports for document creation:

from pylatex import Document, Section, Subsection, Command, Package
from pylatex.base_classes import Environment, LatexObject
from pylatex.utils import NoEscape, escape_latex

Configuration imports:

import pylatex.config
from pylatex.config import Version1, Version2, Default, NextMajor

Basic Usage

from pylatex import Document, Section, Subsection, Command
from pylatex.base_classes import Environment

# Create a new document
doc = Document('basic_example', documentclass='article')

# Add packages
doc.packages.append(Package('amsmath'))

# Add content
with doc.create(Section('Introduction')):
    doc.append('This is a basic PyLaTeX document.')
    
    with doc.create(Subsection('Getting Started')):
        doc.append('PyLaTeX makes LaTeX document generation simple.')

# Generate LaTeX file
doc.generate_tex()

# Compile to PDF (requires LaTeX installation)
doc.generate_pdf(clean_tex=False)

Architecture

PyLaTeX is built around a hierarchical object model that mirrors LaTeX's structure:

  • LatexObject: Base class for all LaTeX elements, handles package dependencies and code generation
  • Container: Objects that can contain other objects (documents, sections, environments)
  • Environment: LaTeX environments with \begin{} and \end{} delimiters
  • Command: LaTeX commands with arguments and options
  • Document: Top-level container that manages the complete LaTeX document

This design allows for composable document construction while maintaining proper LaTeX syntax and automatic package management.

Capabilities

Document Structure and Management

Core document creation, compilation, and structure management including sections, packages, and document-wide settings.

class Document(Environment):
    def __init__(self, default_filepath="default_filepath", *, 
                 documentclass="article", document_options=None, 
                 fontenc="T1", inputenc="utf8", ...): ...
    def generate_tex(self, filepath=None): ...
    def generate_pdf(self, filepath=None, *, clean=True, 
                     clean_tex=True, compiler=None, ...): ...
    def add_color(self, name, model, description): ...
    def set_variable(self, name, value): ...

Document Management

Base Classes and Object Model

Fundamental base classes that provide the foundation for all PyLaTeX objects, including the core inheritance hierarchies and common functionality.

class LatexObject:
    def dumps(self): ...
    def dump(self, file_w): ...
    def generate_tex(self, filepath): ...

class Container(LatexObject):
    def create(self, child): ...
    def dumps_content(self, **kwargs): ...

class Environment(Container):
    def __init__(self, *, options=None, arguments=None, ...): ...

class Command(CommandBase):
    def __init__(self, command=None, arguments=None, options=None, ...): ...

Base Classes

Text Formatting and Basic Elements

Text formatting commands and environments for controlling font sizes, colors, spacing, and basic document elements.

class TextColor(ContainerCommand):
    def __init__(self, color, data): ...

class HugeText(Environment): ...
class LargeText(Environment): ...
class MediumText(Environment): ...
class SmallText(Environment): ...

class NewPage(CommandBase): ...
class LineBreak(CommandBase): ...
class HFill(CommandBase): ...

Text Formatting

Document Sectioning

Hierarchical document structure with chapters, sections, subsections, and automatic numbering and labeling.

class Section(Container):
    def __init__(self, title, numbering=None, *, label=True, **kwargs): ...

class Chapter(Section): ...
class Subsection(Section): ...
class Subsubsection(Section): ...

Sectioning

Tables and Tabular Data

Comprehensive table creation with various table types, formatting options, and cell manipulation capabilities.

class Tabular(Environment):
    def __init__(self, table_spec, data=None, pos=None, *, 
                 row_height=None, col_space=None, ...): ...
    def add_row(self, *cells, color=None, escape=None, 
                mapper=None, strict=True): ...
    def add_hline(self, start=None, end=None, *, color=None, ...): ...

class Table(Float): ...
class Tabularx(Tabular): ...
class LongTable(Tabular): ...

class MultiColumn:
    def __init__(self, size, align, content, *, color=None, data=None): ...

class MultiRow:
    def __init__(self, size, width, content, *, color=None, data=None): ...

Tables

Mathematical Expressions

Mathematical typesetting with equations, matrices, aligned environments, and vector notation.

class Math(Container):
    def __init__(self, *, inline=False, data=None, escape=None): ...

class Alignat(Environment):
    def __init__(self, aligns=2, numbering=True, escape=None): ...

class Matrix(Environment):
    def __init__(self, matrix, *, mtype="p", alignment=None): ...

class VectorName(Command):
    def __init__(self, name): ...

Math

Figures and Graphics

Figure environments, image inclusion, subfigures, and matplotlib integration for scientific and technical documents.

class Figure(Float):
    def add_image(self, filename, *, width=NoEscape(r"0.8\\textwidth"), 
                  placement=NoEscape(r"\\centering")): ...
    def add_plot(self, *args, extension="pdf", **kwargs): ...

class SubFigure(Figure):
    def __init__(self, width=NoEscape(r"0.45\\linewidth"), **kwargs): ...

class StandAloneGraphic(UnsafeCommand):
    def __init__(self, filename, image_options=NoEscape(r"width=0.8\\textwidth"), 
                 extra_arguments=None): ...

Figures

Lists and Enumerations

List environments including itemized lists, numbered lists, and description lists with customization options.

class Itemize(Environment):
    def add_item(self, s): ...

class Enumerate(Environment):
    def __init__(self, enumeration_symbol=None, *, options=None, **kwargs): ...
    def add_item(self, s): ...

class Description(Environment):
    def add_item(self, label, s): ...

Lists

Layout and Positioning

Advanced layout control with positioning, spacing, alignment, and minipage environments for precise document formatting.

class MiniPage(Environment):
    def __init__(self, *, width=NoEscape(r"\\textwidth"), pos=None, 
                 height=None, content_pos=None, align=None, ...): ...

class Center(Environment): ...
class FlushLeft(Environment): ...
class FlushRight(Environment): ...

class HorizontalSpace(CommandBase):
    def __init__(self, size, *, star=True): ...

class VerticalSpace(CommandBase):
    def __init__(self, size, *, star=True): ...

Layout

References and Cross-referencing

Label creation and cross-referencing system for equations, figures, sections, and pages with automatic formatting.

class Label(Command): ...
class Ref(Command): ...
class Pageref(Command): ...
class Eqref(Command): ...
class Autoref(Command): ...
class Hyperref(Command): ...

class Marker(LatexObject):
    def __init__(self, name, prefix=""): ...

References

TikZ Graphics and Plotting

Advanced graphics creation with TikZ including geometric shapes, plots, coordinate systems, and complex diagrams.

class TikZ(Environment): ...

class TikZCoordinate(Command): ...
class TikZNode(Command): ...
class TikZDraw(Command): ...
class TikZPath(Command): ...

class Axis(Environment): ...
class Plot(Command): ...

TikZ Graphics

Physical Quantities and Units

Scientific notation and unit handling with SIunits integration for proper typesetting of measurements and quantities.

class Quantity(Command):
    def __init__(self, quantity, *, options=None, format_cb=None): ...

Quantities

Utilities and Helper Functions

Utility functions for LaTeX escaping, file handling, and string manipulation to support document generation workflows.

class NoEscape(str): ...

def escape_latex(s): ...
def fix_filename(path): ...
def dumps_list(*args, **kwargs): ...

Utilities

Configuration and Settings

Global configuration system for customizing PyLaTeX behavior, including indentation, typography, and table styling preferences.

class Version1:
    """v1.x.y behavior configuration."""
    def __init__(self, **kwargs): ...
    def use(self): ...
    def change(self, **kwargs): ...

class Version2(Version1):
    """v2.x.y behavior configuration."""

# Configuration aliases
Default = Version1
NextMajor = Version2

# Global active configuration
active: Version1

Configuration

Package Management

PyLaTeX automatically manages LaTeX package dependencies. When you use classes that require specific packages, they are automatically added to the document's package list.

from pylatex import Document, Package
from pylatex.math import Matrix

doc = Document()
# Matrix class automatically adds 'amsmath' package
matrix = Matrix([[1, 2], [3, 4]])
doc.append(matrix)

# Manually add packages if needed
doc.packages.append(Package('geometry', options=['margin=1in']))

Error Handling

PyLaTeX provides specific exception types for different error conditions:

class PyLaTeXError(Exception): 
    """Base class for all PyLaTeX exceptions."""

class CompilerError(PyLaTeXError): 
    """Base class for LaTeX compilation related exceptions."""

class TableError(PyLaTeXError): 
    """Base class for all table-related errors."""

class TableRowSizeError(TableError): 
    """Error for wrong table row size."""

Always handle compilation errors when generating PDFs, as they depend on the local LaTeX installation and document content. Use the specific exception types to catch and handle different types of errors appropriately.