or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

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

index.mddocs/

0

# PyLaTeX

1

2

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.

3

4

## Package Information

5

6

- **Package Name**: PyLaTeX

7

- **Language**: Python

8

- **Installation**: `pip install PyLaTeX`

9

10

## Core Imports

11

12

```python

13

import pylatex

14

```

15

16

Common imports for document creation:

17

18

```python

19

from pylatex import Document, Section, Subsection, Command, Package

20

from pylatex.base_classes import Environment, LatexObject

21

from pylatex.utils import NoEscape, escape_latex

22

```

23

24

Configuration imports:

25

26

```python

27

import pylatex.config

28

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

29

```

30

31

## Basic Usage

32

33

```python

34

from pylatex import Document, Section, Subsection, Command

35

from pylatex.base_classes import Environment

36

37

# Create a new document

38

doc = Document('basic_example', documentclass='article')

39

40

# Add packages

41

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

42

43

# Add content

44

with doc.create(Section('Introduction')):

45

doc.append('This is a basic PyLaTeX document.')

46

47

with doc.create(Subsection('Getting Started')):

48

doc.append('PyLaTeX makes LaTeX document generation simple.')

49

50

# Generate LaTeX file

51

doc.generate_tex()

52

53

# Compile to PDF (requires LaTeX installation)

54

doc.generate_pdf(clean_tex=False)

55

```

56

57

## Architecture

58

59

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

60

61

- **LatexObject**: Base class for all LaTeX elements, handles package dependencies and code generation

62

- **Container**: Objects that can contain other objects (documents, sections, environments)

63

- **Environment**: LaTeX environments with \\begin{} and \\end{} delimiters

64

- **Command**: LaTeX commands with arguments and options

65

- **Document**: Top-level container that manages the complete LaTeX document

66

67

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

68

69

## Capabilities

70

71

### Document Structure and Management

72

73

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

74

75

```python { .api }

76

class Document(Environment):

77

def __init__(self, default_filepath="default_filepath", *,

78

documentclass="article", document_options=None,

79

fontenc="T1", inputenc="utf8", ...): ...

80

def generate_tex(self, filepath=None): ...

81

def generate_pdf(self, filepath=None, *, clean=True,

82

clean_tex=True, compiler=None, ...): ...

83

def add_color(self, name, model, description): ...

84

def set_variable(self, name, value): ...

85

```

86

87

[Document Management](./document.md)

88

89

### Base Classes and Object Model

90

91

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

92

93

```python { .api }

94

class LatexObject:

95

def dumps(self): ...

96

def dump(self, file_w): ...

97

def generate_tex(self, filepath): ...

98

99

class Container(LatexObject):

100

def create(self, child): ...

101

def dumps_content(self, **kwargs): ...

102

103

class Environment(Container):

104

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

105

106

class Command(CommandBase):

107

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

108

```

109

110

[Base Classes](./base-classes.md)

111

112

### Text Formatting and Basic Elements

113

114

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

115

116

```python { .api }

117

class TextColor(ContainerCommand):

118

def __init__(self, color, data): ...

119

120

class HugeText(Environment): ...

121

class LargeText(Environment): ...

122

class MediumText(Environment): ...

123

class SmallText(Environment): ...

124

125

class NewPage(CommandBase): ...

126

class LineBreak(CommandBase): ...

127

class HFill(CommandBase): ...

128

```

129

130

[Text Formatting](./text-formatting.md)

131

132

### Document Sectioning

133

134

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

135

136

```python { .api }

137

class Section(Container):

138

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

139

140

class Chapter(Section): ...

141

class Subsection(Section): ...

142

class Subsubsection(Section): ...

143

```

144

145

[Sectioning](./sectioning.md)

146

147

### Tables and Tabular Data

148

149

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

150

151

```python { .api }

152

class Tabular(Environment):

153

def __init__(self, table_spec, data=None, pos=None, *,

154

row_height=None, col_space=None, ...): ...

155

def add_row(self, *cells, color=None, escape=None,

156

mapper=None, strict=True): ...

157

def add_hline(self, start=None, end=None, *, color=None, ...): ...

158

159

class Table(Float): ...

160

class Tabularx(Tabular): ...

161

class LongTable(Tabular): ...

162

163

class MultiColumn:

164

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

165

166

class MultiRow:

167

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

168

```

169

170

[Tables](./tables.md)

171

172

### Mathematical Expressions

173

174

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

175

176

```python { .api }

177

class Math(Container):

178

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

179

180

class Alignat(Environment):

181

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

182

183

class Matrix(Environment):

184

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

185

186

class VectorName(Command):

187

def __init__(self, name): ...

188

```

189

190

[Math](./math.md)

191

192

### Figures and Graphics

193

194

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

195

196

```python { .api }

197

class Figure(Float):

198

def add_image(self, filename, *, width=NoEscape(r"0.8\\textwidth"),

199

placement=NoEscape(r"\\centering")): ...

200

def add_plot(self, *args, extension="pdf", **kwargs): ...

201

202

class SubFigure(Figure):

203

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

204

205

class StandAloneGraphic(UnsafeCommand):

206

def __init__(self, filename, image_options=NoEscape(r"width=0.8\\textwidth"),

207

extra_arguments=None): ...

208

```

209

210

[Figures](./figures.md)

211

212

### Lists and Enumerations

213

214

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

215

216

```python { .api }

217

class Itemize(Environment):

218

def add_item(self, s): ...

219

220

class Enumerate(Environment):

221

def __init__(self, enumeration_symbol=None, *, options=None, **kwargs): ...

222

def add_item(self, s): ...

223

224

class Description(Environment):

225

def add_item(self, label, s): ...

226

```

227

228

[Lists](./lists.md)

229

230

### Layout and Positioning

231

232

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

233

234

```python { .api }

235

class MiniPage(Environment):

236

def __init__(self, *, width=NoEscape(r"\\textwidth"), pos=None,

237

height=None, content_pos=None, align=None, ...): ...

238

239

class Center(Environment): ...

240

class FlushLeft(Environment): ...

241

class FlushRight(Environment): ...

242

243

class HorizontalSpace(CommandBase):

244

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

245

246

class VerticalSpace(CommandBase):

247

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

248

```

249

250

[Layout](./layout.md)

251

252

### References and Cross-referencing

253

254

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

255

256

```python { .api }

257

class Label(Command): ...

258

class Ref(Command): ...

259

class Pageref(Command): ...

260

class Eqref(Command): ...

261

class Autoref(Command): ...

262

class Hyperref(Command): ...

263

264

class Marker(LatexObject):

265

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

266

```

267

268

[References](./references.md)

269

270

### TikZ Graphics and Plotting

271

272

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

273

274

```python { .api }

275

class TikZ(Environment): ...

276

277

class TikZCoordinate(Command): ...

278

class TikZNode(Command): ...

279

class TikZDraw(Command): ...

280

class TikZPath(Command): ...

281

282

class Axis(Environment): ...

283

class Plot(Command): ...

284

```

285

286

[TikZ Graphics](./tikz.md)

287

288

### Physical Quantities and Units

289

290

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

291

292

```python { .api }

293

class Quantity(Command):

294

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

295

```

296

297

[Quantities](./quantities.md)

298

299

### Utilities and Helper Functions

300

301

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

302

303

```python { .api }

304

class NoEscape(str): ...

305

306

def escape_latex(s): ...

307

def fix_filename(path): ...

308

def dumps_list(*args, **kwargs): ...

309

```

310

311

[Utilities](./utilities.md)

312

313

### Configuration and Settings

314

315

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

316

317

```python { .api }

318

class Version1:

319

"""v1.x.y behavior configuration."""

320

def __init__(self, **kwargs): ...

321

def use(self): ...

322

def change(self, **kwargs): ...

323

324

class Version2(Version1):

325

"""v2.x.y behavior configuration."""

326

327

# Configuration aliases

328

Default = Version1

329

NextMajor = Version2

330

331

# Global active configuration

332

active: Version1

333

```

334

335

[Configuration](./configuration.md)

336

337

## Package Management

338

339

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

340

341

```python

342

from pylatex import Document, Package

343

from pylatex.math import Matrix

344

345

doc = Document()

346

# Matrix class automatically adds 'amsmath' package

347

matrix = Matrix([[1, 2], [3, 4]])

348

doc.append(matrix)

349

350

# Manually add packages if needed

351

doc.packages.append(Package('geometry', options=['margin=1in']))

352

```

353

354

## Error Handling

355

356

PyLaTeX provides specific exception types for different error conditions:

357

358

```python { .api }

359

class PyLaTeXError(Exception):

360

"""Base class for all PyLaTeX exceptions."""

361

362

class CompilerError(PyLaTeXError):

363

"""Base class for LaTeX compilation related exceptions."""

364

365

class TableError(PyLaTeXError):

366

"""Base class for all table-related errors."""

367

368

class TableRowSizeError(TableError):

369

"""Error for wrong table row size."""

370

```

371

372

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.