A comprehensive Python library for programmatically creating and compiling LaTeX documents and snippets.
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Comprehensive table creation with various table types, formatting options, and cell manipulation capabilities. PyLaTeX provides a rich set of classes for creating professional-looking tables with support for multi-column layouts, long tables, and advanced styling.
The Tabular class is the foundation for creating tables in LaTeX, providing precise control over column specifications and content.
class Tabular(Environment):
def __init__(self, table_spec, data=None, pos=None, *,
row_height=None, col_space=None, width=None,
booktabs=None, **kwargs):
"""
Create a basic tabular environment.
Parameters:
- table_spec: str, column specification ('lrc', 'p{3cm}', etc.)
- data: list, initial table data
- pos: list, vertical positioning options
- row_height: float, relative row height multiplier
- col_space: str, spacing between columns
- width: int, number of columns (auto-calculated if None)
- booktabs: bool, use professional-style booktabs formatting
"""
def add_row(self, *cells, color=None, escape=None,
mapper=None, strict=True):
"""
Add a row to the table.
Parameters:
- *cells: content for each cell in the row
- color: str, row background color
- escape: bool, escape special LaTeX characters
- mapper: callable, function to map cell content
- strict: bool, enforce column count matching
"""
def add_hline(self, start=None, end=None, *, color=None):
"""
Add horizontal line across table.
Parameters:
- start: int, starting column (1-indexed)
- end: int, ending column (1-indexed)
- color: str, line color
"""
def add_multicolumn(self, size, align, content, *, cells=None):
"""
Add multi-column cell to current row.
Parameters:
- size: int, number of columns to span
- align: str, column alignment ('l', 'c', 'r')
- content: str or LatexObject, cell content
- cells: list, additional cells for the row
"""
def add_multirow(self, size, align, content, *, hlines=True,
cells=None, color=None):
"""
Add multi-row cell to table.
Parameters:
- size: int, number of rows to span
- align: str, column alignment
- content: str or LatexObject, cell content
- hlines: bool, add horizontal lines
- cells: list, additional cells
- color: str, cell background color
"""Usage example:
from pylatex import Document, Tabular, Command
from pylatex.table import MultiColumn, MultiRow
doc = Document()
# Basic table
with doc.create(Tabular('|c|c|c|')) as table:
table.add_hline()
table.add_row(('Name', 'Age', 'City'))
table.add_hline()
table.add_row(('Alice', 25, 'New York'))
table.add_row(('Bob', 30, 'London'))
table.add_hline()
# Table with booktabs styling
geometry_options = {"margin": "1in"}
doc = Document(geometry_options=geometry_options)
with doc.create(Tabular('lcc', booktabs=True)) as table:
table.add_row(['Product', 'Price', 'Quantity'])
table.add_hline()
table.add_row(['Widget A', '$10.99', '50'])
table.add_row(['Widget B', '$15.99', '30'])The Table class creates floating table environments that can be positioned automatically by LaTeX.
class Table(Float):
def __init__(self, position=None, **kwargs):
"""
Create a floating table environment.
Parameters:
- position: str, float positioning ('h', 't', 'b', 'p', '!')
"""Usage example:
from pylatex import Document, Section, Tabular
from pylatex.table import Table
from pylatex import Command
doc = Document()
with doc.create(Section('Sales Data')):
with doc.create(Table(position='htbp')) as table:
table.add_caption('Quarterly Sales Report')
with table.create(Tabular('|l|c|c|c|')) as tabular:
tabular.add_hline()
tabular.add_row(['Quarter', 'Revenue', 'Profit', 'Growth'])
tabular.add_hline()
tabular.add_row(['Q1', '$100K', '$20K', '5%'])
tabular.add_row(['Q2', '$120K', '$25K', '8%'])
tabular.add_hline()Advanced table environments for specific use cases and enhanced functionality.
class Tabularx(Tabular):
def __init__(self, width, columns, *, width_argument=None, **kwargs):
"""
Extended tabular with automatic column width adjustment.
Parameters:
- width: str, total table width
- columns: str, column specification with 'X' columns
- width_argument: str, width specification format
Requires:
- tabularx package
"""
class LongTable(Tabular):
"""
Multi-page table environment.
Requires:
- longtable package
"""
class Tabu(Tabular):
"""
Enhanced tabular environment with advanced features.
Requires:
- longtabu package
"""
class LongTabu(Tabu):
"""
Multi-page tabu table.
Requires:
- longtabu package
"""
class LongTabularx(Tabular):
"""
Multi-page tabularx table.
Requires:
- ltxtable package
"""Usage example:
from pylatex import Document, NoEscape
from pylatex.table import Tabularx, LongTable
doc = Document()
# Automatic width adjustment
with doc.create(Tabularx(NoEscape(r'\textwidth'), 'X[l] X[c] X[r]')) as table:
table.add_row(['Left aligned', 'Centered', 'Right aligned'])
table.add_row(['This column adjusts', 'This too', 'And this'])
# Long table for multi-page content
with doc.create(LongTable('|l|p{4cm}|')) as longtable:
longtable.add_hline()
longtable.add_row(['Item', 'Description'])
longtable.add_hline()
longtable.end_table_header() # Repeat on each page
for i in range(100):
longtable.add_row([f'Item {i}', f'Description of item {i}'])Classes for creating cells that span multiple columns or rows.
class MultiColumn:
def __init__(self, size, align, content, *, color=None, data=None):
"""
Cell spanning multiple columns.
Parameters:
- size: int, number of columns to span
- align: str, alignment ('l', 'c', 'r')
- content: str or LatexObject, cell content
- color: str, background color
- data: additional cell data
"""
class MultiRow:
def __init__(self, size, width, content, *, color=None, data=None):
"""
Cell spanning multiple rows.
Parameters:
- size: int, number of rows to span
- width: str, cell width specification
- content: str or LatexObject, cell content
- color: str, background color
- data: additional cell data
Requires:
- multirow package
"""
class ColumnType:
def __init__(self, name, base_type, modifier):
"""
Custom column type definition.
Parameters:
- name: str, new column type name
- base_type: str, base column type to extend
- modifier: str, LaTeX code to modify the column
Requires:
- array package
"""Usage example:
from pylatex import Document, Tabular
from pylatex.table import MultiColumn, MultiRow
doc = Document()
with doc.create(Tabular('|c|c|c|c|')) as table:
table.add_hline()
# Multi-column header
table.add_row([MultiColumn(4, align='c', content='Annual Report')])
table.add_hline()
# Regular headers
table.add_row(['Quarter', 'Revenue', 'Expenses', 'Profit'])
table.add_hline()
# Multi-row cell
table.add_row([MultiRow(2, width='*', content='H1'),
'$100K', '$60K', '$40K'])
table.add_row(['', '$120K', '$70K', '$50K'])
table.add_hline()
table.add_row([MultiRow(2, width='*', content='H2'),
'$110K', '$65K', '$45K'])
table.add_row(['', '$130K', '$75K', '$55K'])
table.add_hline()Common column specification patterns:
'lrc' (left, right, center)'p{3cm}' (paragraph column)'|l|c|r|' (borders between columns)'||c||' (double lines)'l|p{2cm}|r' (combination)from pylatex import Document, Package
from pylatex.table import Tabular
doc = Document()
doc.packages.append(Package('booktabs'))
doc.packages.append(Package('xcolor', options=['table']))
# Professional table styling
with doc.create(Tabular('lcc', booktabs=True)) as table:
table.add_row(['Item', 'Value', 'Change'], mapper=lambda x: Command('textbf', x))
table.add_hline()
table.add_row(['Revenue', '$1.2M', '+15%'])
table.add_row(['Profit', '$300K', '+22%'], color='lightgray')
table.add_row(['Growth', '18%', '+3%'])from pylatex import Document, Command, NoEscape
from pylatex.table import Tabular
doc = Document()
# Custom spacing and colors
with doc.create(Tabular('lcc', row_height=1.5, col_space='10pt')) as table:
# Colored rows
table.add_row(['Header 1', 'Header 2', 'Header 3'], color='lightblue')
table.add_row(['Data 1', 'Data 2', 'Data 3'])
table.add_row(['Data 4', 'Data 5', 'Data 6'], color='lightgray')
# Colored lines
table.add_hline(color='red')from pylatex import Document, Section
from pylatex.table import Table, Tabular
def create_data_table(data, headers):
"""Create table from data structure."""
with doc.create(Table(position='htbp')) as table:
table.add_caption('Generated Data Table')
# Calculate column spec based on data
col_spec = 'l' + 'c' * (len(headers) - 1)
with table.create(Tabular(col_spec, booktabs=True)) as tabular:
# Add headers
tabular.add_row(headers)
tabular.add_hline()
# Add data rows
for row in data:
tabular.add_row(row)
# Usage
doc = Document()
headers = ['Name', 'Age', 'Department', 'Salary']
employee_data = [
['Alice Johnson', 28, 'Engineering', '$75,000'],
['Bob Smith', 34, 'Marketing', '$65,000'],
['Carol Davis', 29, 'Design', '$70,000']
]
create_data_table(employee_data, headers)from pylatex import Document, Command, NoEscape
from pylatex.table import Tabular, MultiColumn, MultiRow
doc = Document()
# Complex business report table
with doc.create(Tabular('|l|c|c|c|c|')) as table:
table.add_hline()
# Title row
table.add_row([MultiColumn(5, align='c',
content=Command('textbf', 'Financial Summary'))])
table.add_hline()
# Period headers
table.add_row(['', MultiColumn(2, align='c', content='2023'),
MultiColumn(2, align='c', content='2024')])
table.add_hline()
# Quarter headers
table.add_row(['Metric', 'Q3', 'Q4', 'Q1', 'Q2'])
table.add_hline()
# Data with multi-row categories
table.add_row([MultiRow(2, width='*', content='Revenue'),
'$1.2M', '$1.5M', '$1.8M', '$2.1M'])
table.add_row(['', '(+8%)', '(+25%)', '(+20%)', '(+17%)'])
table.add_hline()
table.add_row([MultiRow(2, width='*', content='Profit'),
'$240K', '$350K', '$450K', '$580K'])
table.add_row(['', '(+12%)', '(+46%)', '(+29%)', '(+29%)'])
table.add_hline()class TableError(Exception):
"""Base class for table-related errors."""
class TableRowSizeError(TableError):
"""Raised when row size doesn't match table specification."""Tables automatically validate row sizes against column specifications and provide helpful error messages when mismatches occur.
Different table types require specific LaTeX packages:
tabularx packagelongtable packagelongtabu packagemultirow packagebooktabs packagexcolor package with table optionPyLaTeX automatically manages these dependencies when you use the corresponding classes.
Install with Tessl CLI
npx tessl i tessl/pypi-pylatex