0
# Media and Document Composition
1
2
Functionality for inserting images, composing sub-documents, and handling text with special characters within templates. These capabilities enable complex document assembly and rich media integration.
3
4
## Capabilities
5
6
### InlineImage Class
7
8
Class for generating inline images in templates with precise control over dimensions and positioning.
9
10
```python { .api }
11
class InlineImage:
12
def __init__(self, tpl, image_descriptor, width=None, height=None, anchor=None):
13
"""
14
Initialize InlineImage for insertion into template.
15
16
Parameters:
17
- tpl: DocxTemplate instance reference
18
- image_descriptor: Path to image file or file-like object
19
- width: Image width (in EMUs, inches, or Inches() object)
20
- height: Image height (in EMUs, inches, or Inches() object)
21
- anchor: Optional URL anchor for image hyperlink
22
"""
23
```
24
25
### InlineImage Properties
26
27
Access to image configuration and template reference.
28
29
```python { .api }
30
@property
31
def tpl:
32
"""Reference to DocxTemplate instance."""
33
34
@property
35
def image_descriptor:
36
"""Path or file-like object for image source."""
37
38
@property
39
def width:
40
"""Image width dimension."""
41
42
@property
43
def height:
44
"""Image height dimension."""
45
46
@property
47
def anchor:
48
"""URL anchor for hyperlink (optional)."""
49
```
50
51
### InlineImage String Methods
52
53
Methods for converting image to XML representation for template insertion.
54
55
```python { .api }
56
def __str__(self) -> str:
57
"""Return XML representation of inline image."""
58
59
def __unicode__(self) -> str:
60
"""Return Unicode XML representation of inline image."""
61
62
def __html__(self) -> str:
63
"""Return HTML-like representation of inline image."""
64
```
65
66
### Subdoc Class
67
68
Class for sub-documents that can be inserted into master documents, enabling complex document composition and modular content assembly.
69
70
```python { .api }
71
class Subdoc:
72
def __init__(self, tpl, docpath=None):
73
"""
74
Initialize Subdoc for document composition.
75
76
Parameters:
77
- tpl: DocxTemplate instance reference
78
- docpath: Optional path to existing document to use as base
79
"""
80
```
81
82
### Subdoc Properties
83
84
Access to document instances and template reference.
85
86
```python { .api }
87
@property
88
def tpl:
89
"""Reference to DocxTemplate instance."""
90
91
@property
92
def docx:
93
"""Main document reference."""
94
95
@property
96
def subdocx:
97
"""Sub-document instance."""
98
```
99
100
### Subdoc Document Methods
101
102
The Subdoc class delegates to python-docx Document methods via `__getattr__`, providing access to all document creation capabilities:
103
104
```python { .api }
105
# Document content creation methods (delegated to python-docx)
106
def add_paragraph(self, text='', style=None): ...
107
def add_table(self, rows, cols, style=None): ...
108
def add_picture(self, image_path_or_stream, width=None, height=None): ...
109
def add_heading(self, text='', level=1): ...
110
def add_page_break(self): ...
111
# ... and all other python-docx Document methods
112
```
113
114
### Subdoc String Methods
115
116
Methods for converting subdocument to XML representation for template insertion.
117
118
```python { .api }
119
def __str__(self) -> str:
120
"""Return XML representation of subdocument."""
121
122
def __unicode__(self) -> str:
123
"""Return Unicode XML representation of subdocument."""
124
125
def __html__(self) -> str:
126
"""Return HTML-like representation of subdocument."""
127
```
128
129
### Listing Class
130
131
Class for managing text with newlines and special characters while preserving template styling. Useful for code listings, addresses, and multi-line formatted text.
132
133
```python { .api }
134
class Listing:
135
def __init__(self, text):
136
"""
137
Initialize Listing with text content.
138
139
Parameters:
140
- text: Text content with newlines and special characters
141
"""
142
```
143
144
### Listing String Methods
145
146
Methods for converting listing to escaped XML representation.
147
148
```python { .api }
149
def __str__(self) -> str:
150
"""Return escaped XML representation of listing text."""
151
152
def __unicode__(self) -> str:
153
"""Return Unicode escaped XML representation of listing text."""
154
155
def __html__(self) -> str:
156
"""Return HTML-like representation of listing text."""
157
```
158
159
## Usage Examples
160
161
### Image Insertion
162
163
```python
164
from docxtpl import DocxTemplate, InlineImage
165
from docx.shared import Inches
166
167
doc = DocxTemplate("template.docx")
168
169
# Create inline image with specific dimensions
170
logo = InlineImage(doc, "company_logo.png", width=Inches(2), height=Inches(1))
171
172
# Image with hyperlink
173
chart_url = doc.build_url_id("https://example.com/chart-details")
174
chart = InlineImage(doc, "sales_chart.png", width=Inches(4), height=Inches(3), anchor=chart_url)
175
176
context = {
177
'company_logo': logo,
178
'sales_chart': chart
179
}
180
181
doc.render(context)
182
doc.save("report_with_images.docx")
183
```
184
185
### Dynamic Image Sizing
186
187
```python
188
from docxtpl import DocxTemplate, InlineImage
189
from docx.shared import Inches, Cm
190
191
doc = DocxTemplate("gallery_template.docx")
192
193
# Different image sizes
194
images = []
195
image_files = ["photo1.jpg", "photo2.jpg", "photo3.jpg"]
196
sizes = [Inches(2), Cm(5), Inches(1.5)]
197
198
for img_file, size in zip(image_files, sizes):
199
img = InlineImage(doc, img_file, width=size, height=size)
200
images.append(img)
201
202
context = {
203
'gallery_images': images
204
}
205
206
doc.render(context)
207
doc.save("photo_gallery.docx")
208
```
209
210
### Subdocument Composition
211
212
```python
213
from docxtpl import DocxTemplate, Subdoc
214
215
doc = DocxTemplate("main_template.docx")
216
217
# Create subdocument with content
218
subdoc = doc.new_subdoc()
219
220
# Add content to subdocument using python-docx methods
221
subdoc.add_heading("Technical Specifications", level=2)
222
subdoc.add_paragraph("This section contains detailed specifications.")
223
224
# Create table in subdocument
225
table = subdoc.add_table(rows=3, cols=2)
226
table.cell(0, 0).text = "Component"
227
table.cell(0, 1).text = "Value"
228
table.cell(1, 0).text = "CPU"
229
table.cell(1, 1).text = "Intel i7"
230
table.cell(2, 0).text = "RAM"
231
table.cell(2, 1).text = "16GB"
232
233
context = {
234
'technical_details': subdoc
235
}
236
237
doc.render(context)
238
doc.save("complete_document.docx")
239
```
240
241
### Complex Document Assembly
242
243
```python
244
from docxtpl import DocxTemplate, Subdoc, InlineImage
245
from docx.shared import Inches
246
247
doc = DocxTemplate("complex_template.docx")
248
249
# Create multiple subdocuments
250
intro_section = doc.new_subdoc()
251
intro_section.add_heading("Introduction", level=1)
252
intro_section.add_paragraph("This document presents our quarterly analysis.")
253
254
results_section = doc.new_subdoc()
255
results_section.add_heading("Results", level=1)
256
results_section.add_paragraph("Key findings from our analysis:")
257
258
# Add image to results section
259
chart_img = InlineImage(doc, "quarterly_chart.png", width=Inches(5))
260
results_section.add_paragraph().add_run().add_picture(chart_img.image_descriptor)
261
262
context = {
263
'introduction': intro_section,
264
'results': results_section,
265
'executive_signature': InlineImage(doc, "signature.png", width=Inches(2))
266
}
267
268
doc.render(context)
269
doc.save("quarterly_report.docx")
270
```
271
272
### Text Listings and Special Characters
273
274
```python
275
from docxtpl import DocxTemplate, Listing
276
277
doc = DocxTemplate("code_template.docx")
278
279
# Code listing with proper formatting
280
python_code = Listing("""def calculate_total(items):
281
total = 0
282
for item in items:
283
total += item['price'] * item['quantity']
284
return total
285
286
# Example usage
287
items = [
288
{'name': 'Widget', 'price': 10.00, 'quantity': 5},
289
{'name': 'Gadget', 'price': 25.00, 'quantity': 2}
290
]
291
result = calculate_total(items)""")
292
293
# Address with line breaks
294
address = Listing("""John Doe
295
123 Main Street
296
Apartment 4B
297
New York, NY 10001
298
United States""")
299
300
# Text with special characters
301
special_text = Listing("Special chars: < > & \" ' \n\nNew line after special chars")
302
303
context = {
304
'code_example': python_code,
305
'customer_address': address,
306
'notes': special_text
307
}
308
309
doc.render(context)
310
doc.save("formatted_document.docx")
311
```
312
313
### Mixed Media Document
314
315
```python
316
from docxtpl import DocxTemplate, InlineImage, Subdoc, Listing, RichText
317
from docx.shared import Inches
318
319
doc = DocxTemplate("mixed_media_template.docx")
320
321
# Header image
322
header_img = InlineImage(doc, "header_banner.png", width=Inches(6))
323
324
# Rich text introduction
325
intro = RichText()
326
intro.add("Welcome to our ", bold=False)
327
intro.add("Annual Report 2024", bold=True, color="0066CC", size=14)
328
329
# Code listing
330
sample_code = Listing("""# Configuration
331
SERVER_URL = "https://api.example.com"
332
API_KEY = "your-api-key-here"
333
TIMEOUT = 30""")
334
335
# Subdocument with mixed content
336
details = doc.new_subdoc()
337
details.add_heading("Technical Details", level=2)
338
details.add_paragraph("Architecture overview:")
339
arch_img = InlineImage(doc, "architecture_diagram.png", width=Inches(4))
340
details.add_paragraph("System Architecture").add_run()._element.append(arch_img._element)
341
342
context = {
343
'header_banner': header_img,
344
'introduction': intro,
345
'configuration': sample_code,
346
'technical_section': details
347
}
348
349
doc.render(context)
350
doc.save("mixed_media_report.docx")
351
```