or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.mdmedia-composition.mdrich-text.mdtemplate-processing.md

index.mddocs/

0

# DocxTpl

1

2

A powerful Python library that uses docx files as Jinja2 templates. DocxTpl bridges the gap between python-docx for document manipulation and Jinja2 for template processing, enabling dynamic Word document generation from templates with embedded variables, loops, conditionals, and rich formatting capabilities.

3

4

## Package Information

5

6

- **Package Name**: docxtpl

7

- **Language**: Python

8

- **Installation**: `pip install docxtpl`

9

- **Dependencies**: python-docx>=1.1.1, docxcompose, jinja2, lxml

10

11

## Core Imports

12

13

```python

14

from docxtpl import DocxTemplate

15

```

16

17

Complete imports for all functionality:

18

19

```python

20

from docxtpl import (

21

DocxTemplate, # Main template class

22

RichText, R, # Rich text formatting

23

RichTextParagraph, RP, # Rich text paragraphs

24

InlineImage, # Image insertion

25

Subdoc, # Document composition

26

Listing # Text with special characters

27

)

28

```

29

30

## Basic Usage

31

32

```python

33

from docxtpl import DocxTemplate

34

35

# Load a Word document as template

36

doc = DocxTemplate("template.docx")

37

38

# Prepare context data

39

context = {

40

'company_name': 'Example Corp',

41

'items': [

42

{'name': 'Product A', 'price': 100},

43

{'name': 'Product B', 'price': 200}

44

]

45

}

46

47

# Render the template with context data

48

doc.render(context)

49

50

# Save the rendered document

51

doc.save("output.docx")

52

```

53

54

Command-line usage:

55

56

```bash

57

python -m docxtpl [-h] [-o] [-q] template.docx data.json output.docx

58

```

59

60

CLI options:

61

- `-o, --overwrite`: Overwrite output file without confirmation if it exists

62

- `-q, --quiet`: Do not display unnecessary messages

63

- `-h, --help`: Show help message and exit

64

65

## Architecture

66

67

DocxTpl's architecture centers around the DocxTemplate class that orchestrates:

68

69

- **Template Processing**: Jinja2 integration for variables, loops, and conditionals in Word documents

70

- **Rich Content**: Specialized classes for formatted text, images, and complex document elements

71

- **Document Structure**: Support for headers, footers, tables, and document composition

72

- **Media Management**: Intelligent handling of images and embedded objects with replacement capabilities

73

74

The design allows Word documents to serve as visual templates while maintaining programmatic control over content generation.

75

76

## Capabilities

77

78

### Core Template Processing

79

80

Main functionality for loading Word documents as templates, rendering them with context data, and managing the template lifecycle.

81

82

```python { .api }

83

class DocxTemplate:

84

def __init__(self, template_file: Union[IO[bytes], str, os.PathLike]) -> None: ...

85

def render(self, context: Dict[str, Any], jinja_env: Optional[Environment] = None, autoescape: bool = False) -> None: ...

86

def save(self, filename: Union[IO[bytes], str, os.PathLike], *args, **kwargs) -> None: ...

87

```

88

89

[Core Template Processing](./template-processing.md)

90

91

### Rich Text Formatting

92

93

Advanced text formatting capabilities for creating rich content within templates, including styled text, hyperlinks, and complex paragraph formatting.

94

95

```python { .api }

96

class RichText:

97

def __init__(self, text=None, **text_prop): ...

98

def add(self, text, style=None, color=None, highlight=None, size=None,

99

subscript=None, superscript=None, bold=False, italic=False,

100

underline=False, strike=False, font=None, url_id=None,

101

rtl=False, lang=None): ...

102

103

class RichTextParagraph:

104

def __init__(self, text=None, **text_prop): ...

105

def add(self, text, parastyle=None): ...

106

```

107

108

[Rich Text Formatting](./rich-text.md)

109

110

### Media and Document Composition

111

112

Functionality for inserting images, composing sub-documents, and handling media replacement within templates.

113

114

```python { .api }

115

class InlineImage:

116

def __init__(self, tpl, image_descriptor, width=None, height=None, anchor=None): ...

117

118

class Subdoc:

119

def __init__(self, tpl, docpath=None): ...

120

121

class Listing:

122

def __init__(self, text): ...

123

```

124

125

[Media and Document Composition](./media-composition.md)

126

127

## Types

128

129

```python { .api }

130

from typing import Union, Dict, Any, Optional, IO, Set

131

from os import PathLike

132

from jinja2 import Environment

133

134

# Template file types

135

TemplateFile = Union[IO[bytes], str, PathLike]

136

137

# Context data for template rendering

138

Context = Dict[str, Any]

139

140

# Jinja2 environment for custom template processing

141

JinjaEnvironment = Optional[Environment]

142

```