docform 0.21.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,927 @@
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Created : 2015-03-12
4
+
5
+ @author: Eric Lapouyade
6
+ """
7
+ from __future__ import annotations
8
+
9
+ from os import PathLike
10
+ from typing import TYPE_CHECKING, Any, Optional, IO, Union, Dict, Set
11
+ import functools
12
+ import io
13
+ from lxml import etree
14
+ from docx import Document
15
+ from docx.opc.oxml import parse_xml
16
+ from docx.opc.part import XmlPart
17
+ import docx.oxml.ns
18
+ from docx.opc.constants import RELATIONSHIP_TYPE as REL_TYPE
19
+ from jinja2 import Environment, Template, meta
20
+ from jinja2.exceptions import TemplateError
21
+
22
+ try:
23
+ from html import escape # noqa: F401
24
+ except ImportError:
25
+ # cgi.escape is deprecated in python 3.7
26
+ from cgi import escape # noqa: F401
27
+ import re
28
+ import binascii
29
+ import os
30
+ import zipfile
31
+
32
+ if TYPE_CHECKING:
33
+ from .subdoc import Subdoc
34
+
35
+
36
+ class DocxTemplate(object):
37
+ """Class for managing docx files as they were jinja2 templates"""
38
+
39
+ HEADER_URI = (
40
+ "http://schemas.openxmlformats.org/officeDocument/2006/relationships/header"
41
+ )
42
+ FOOTER_URI = (
43
+ "http://schemas.openxmlformats.org/officeDocument/2006/relationships/footer"
44
+ )
45
+
46
+ def __init__(self, template_file: Union[IO[bytes], str, PathLike]) -> None:
47
+ self.template_file = template_file
48
+ self.reset_replacements()
49
+ self.docx = None
50
+ self.is_rendered = False
51
+ self.is_saved = False
52
+ self.allow_missing_pics = False
53
+
54
+ def init_docx(self, reload: bool = True):
55
+ if not self.docx or (self.is_rendered and reload):
56
+ self.docx = Document(self.template_file)
57
+ self.is_rendered = False
58
+
59
+ def render_init(self):
60
+ self.init_docx()
61
+ self.pic_map = {}
62
+ self.current_rendering_part = None
63
+ self.docx_ids_index = 1000
64
+ self.is_saved = False
65
+
66
+ def __getattr__(self, name):
67
+ return getattr(self.docx, name)
68
+
69
+ def xml_to_string(self, xml, encoding="unicode"):
70
+ # Be careful : pretty_print MUST be set to False, otherwise patch_xml()
71
+ # won't work properly
72
+ return etree.tostring(xml, encoding="unicode", pretty_print=False)
73
+
74
+ def get_docx(self):
75
+ self.init_docx()
76
+ return self.docx
77
+
78
+ def get_xml(self):
79
+ return self.xml_to_string(self.docx._element.body)
80
+
81
+ def write_xml(self, filename):
82
+ with open(filename, "w") as fh:
83
+ fh.write(self.get_xml())
84
+
85
+ def patch_xml(self, src_xml):
86
+ """Make a lots of cleaning to have a raw xml understandable by jinja2 :
87
+ strip all unnecessary xml tags, manage table cell background color and colspan,
88
+ unescape html entities, etc..."""
89
+
90
+ # replace {<something>{ by {{ ( works with {{ }} {% and %} {# and #})
91
+ src_xml = re.sub(
92
+ r"(?<={)(<[^>]*>)+(?=[\{%\#])|(?<=[%\}\#])(<[^>]*>)+(?=\})",
93
+ "",
94
+ src_xml,
95
+ flags=re.DOTALL,
96
+ )
97
+
98
+ # replace {{<some tags>jinja2 stuff<some other tags>}} by {{jinja2 stuff}}
99
+ # same thing with {% ... %} and {# #}
100
+ # "jinja2 stuff" could a variable, a 'if' etc... anything jinja2 will understand
101
+ def striptags(m):
102
+ return re.sub(
103
+ "</w:t>.*?(<w:t>|<w:t [^>]*>)", "", m.group(0), flags=re.DOTALL
104
+ )
105
+
106
+ src_xml = re.sub(
107
+ r"{%(?:(?!%}).)*|{#(?:(?!#}).)*|{{(?:(?!}}).)*",
108
+ striptags,
109
+ src_xml,
110
+ flags=re.DOTALL,
111
+ )
112
+
113
+ # manage table cell colspan
114
+ def colspan(m):
115
+ cell_xml = m.group(1) + m.group(3)
116
+ cell_xml = re.sub(
117
+ r"<w:r[ >](?:(?!<w:r[ >]).)*<w:t></w:t>.*?</w:r>",
118
+ "",
119
+ cell_xml,
120
+ flags=re.DOTALL,
121
+ )
122
+ cell_xml = re.sub(r"<w:gridSpan[^/]*/>", "", cell_xml, count=1)
123
+ return re.sub(
124
+ r"(<w:tcPr[^>]*>)",
125
+ r'\1<w:gridSpan w:val="{{%s}}"/>' % m.group(2),
126
+ cell_xml,
127
+ )
128
+
129
+ src_xml = re.sub(
130
+ r"(<w:tc[ >](?:(?!<w:tc[ >]).)*){%\s*colspan\s+([^%]*)\s*%}(.*?</w:tc>)",
131
+ colspan,
132
+ src_xml,
133
+ flags=re.DOTALL,
134
+ )
135
+
136
+ # manage table cell background color
137
+ def cellbg(m):
138
+ cell_xml = m.group(1) + m.group(3)
139
+ cell_xml = re.sub(
140
+ r"<w:r[ >](?:(?!<w:r[ >]).)*<w:t></w:t>.*?</w:r>",
141
+ "",
142
+ cell_xml,
143
+ flags=re.DOTALL,
144
+ )
145
+ cell_xml = re.sub(r"<w:shd[^/]*/>", "", cell_xml, count=1)
146
+ return re.sub(
147
+ r"(<w:tcPr[^>]*>)",
148
+ r'\1<w:shd w:val="clear" w:color="auto" w:fill="{{%s}}"/>' % m.group(2),
149
+ cell_xml,
150
+ )
151
+
152
+ src_xml = re.sub(
153
+ r"(<w:tc[ >](?:(?!<w:tc[ >]).)*){%\s*cellbg\s+([^%]*)\s*%}(.*?</w:tc>)",
154
+ cellbg,
155
+ src_xml,
156
+ flags=re.DOTALL,
157
+ )
158
+
159
+ # ensure space preservation
160
+ src_xml = re.sub(
161
+ r"<w:t>((?:(?!<w:t>).)*)({{.*?}}|{%.*?%})",
162
+ r'<w:t xml:space="preserve">\1\2',
163
+ src_xml,
164
+ flags=re.DOTALL,
165
+ )
166
+ src_xml = re.sub(
167
+ r"({{r\s.*?}}|{%r\s.*?%})",
168
+ r'</w:t></w:r><w:r><w:t xml:space="preserve">\1</w:t></w:r><w:r><w:t xml:space="preserve">',
169
+ src_xml,
170
+ flags=re.DOTALL,
171
+ )
172
+
173
+ # {%- will merge with previous paragraph text
174
+ src_xml = re.sub(r"</w:t>(?:(?!</w:t>).)*?{%-", "{%", src_xml, flags=re.DOTALL)
175
+ # -%} will merge with next paragraph text
176
+ src_xml = re.sub(
177
+ r"-%}(?:(?!<w:t[ >]|{%|{{).)*?<w:t[^>]*?>", "%}", src_xml, flags=re.DOTALL
178
+ )
179
+
180
+ for y in ["tr", "tc", "p", "r"]:
181
+ # replace into xml code the row/paragraph/run containing
182
+ # {%y xxx %} or {{y xxx}} template tag
183
+ # by {% xxx %} or {{ xx }} without any surrounding <w:y> tags :
184
+ # This is mandatory to have jinja2 generating correct xml code
185
+ pat = (
186
+ r"<w:%(y)s[ >](?:(?!<w:%(y)s[ >]).)*({%%|{{)%(y)s ([^}%%]*(?:%%}|}})).*?</w:%(y)s>"
187
+ % {"y": y}
188
+ )
189
+ src_xml = re.sub(pat, r"\1 \2", src_xml, flags=re.DOTALL)
190
+
191
+ for y in ["tr", "tc", "p"]:
192
+ # same thing, but for {#y xxx #} (but not where y == 'r', since that
193
+ # makes less sense to use comments in that context
194
+ pat = (
195
+ r"<w:%(y)s[ >](?:(?!<w:%(y)s[ >]).)*({#)%(y)s ([^}#]*(?:#})).*?</w:%(y)s>"
196
+ % {"y": y}
197
+ )
198
+ src_xml = re.sub(pat, r"\1 \2", src_xml, flags=re.DOTALL)
199
+
200
+ # add vMerge
201
+ # use {% vm %} to make this table cell and its copies
202
+ # be vertically merged within a {% for %}
203
+ def v_merge_tc(m):
204
+ def v_merge(m1):
205
+ return (
206
+ '<w:vMerge w:val="{% if loop.first %}restart{% else %}continue{% endif %}"/>'
207
+ + m1.group(1) # Everything between ``</w:tcPr>`` and ``<w:t>``.
208
+ + "{% if loop.first %}"
209
+ + m1.group(2) # Everything before ``{% vm %}``.
210
+ + m1.group(3) # Everything after ``{% vm %}``.
211
+ + "{% endif %}"
212
+ + m1.group(4) # ``</w:t>``.
213
+ )
214
+
215
+ return re.sub(
216
+ r"(</w:tcPr[ >].*?<w:t(?:.*?)>)(.*?)(?:{%\s*vm\s*%})(.*?)(</w:t>)",
217
+ v_merge,
218
+ m.group(),
219
+ # Everything between ``</w:tc>`` and ``</w:tc>`` with ``{% vm %}`` inside.
220
+ flags=re.DOTALL,
221
+ )
222
+
223
+ src_xml = re.sub(
224
+ r"<w:tc[ >](?:(?!<w:tc[ >]).)*?{%\s*vm\s*%}.*?</w:tc[ >]",
225
+ v_merge_tc,
226
+ src_xml,
227
+ flags=re.DOTALL,
228
+ )
229
+
230
+ # Use ``{% hm %}`` to make table cell become horizontally merged within
231
+ # a ``{% for %}``.
232
+ def h_merge_tc(m):
233
+ xml_to_patch = (
234
+ m.group()
235
+ ) # Everything between ``</w:tc>`` and ``</w:tc>`` with ``{% hm %}`` inside.
236
+
237
+ def with_gridspan(m1):
238
+ return (
239
+ m1.group(1) # ``w:gridSpan w:val="``.
240
+ + "{{ "
241
+ + m1.group(2)
242
+ + " * loop.length }}" # Content of ``w:val``, multiplied by loop length.
243
+ + m1.group(3) # Closing quotation mark.
244
+ )
245
+
246
+ def without_gridspan(m2):
247
+ return (
248
+ '<w:gridSpan w:val="{{ loop.length }}"/>'
249
+ + m2.group(1) # Everything between ``</w:tcPr>`` and ``<w:t>``.
250
+ + m2.group(2) # Everything before ``{% hm %}``.
251
+ + m2.group(3) # Everything after ``{% hm %}``.
252
+ + m2.group(4) # ``</w:t>``.
253
+ )
254
+
255
+ if re.search(r"w:gridSpan", xml_to_patch):
256
+ # Simple case, there's already ``gridSpan``, multiply its value.
257
+
258
+ xml = re.sub(
259
+ r'(w:gridSpan w:val=")(\d+)(")',
260
+ with_gridspan,
261
+ xml_to_patch,
262
+ flags=re.DOTALL,
263
+ )
264
+ xml = re.sub(
265
+ r"{%\s*hm\s*%}",
266
+ "",
267
+ xml, # Patched xml.
268
+ flags=re.DOTALL,
269
+ )
270
+ else:
271
+ # There're no ``gridSpan``, add one.
272
+ xml = re.sub(
273
+ r"(</w:tcPr[ >].*?<w:t(?:.*?)>)(.*?)(?:{%\s*hm\s*%})(.*?)(</w:t>)",
274
+ without_gridspan,
275
+ xml_to_patch,
276
+ flags=re.DOTALL,
277
+ )
278
+
279
+ # Discard every other cell generated in loop.
280
+ return "{% if loop.first %}" + xml + "{% endif %}"
281
+
282
+ src_xml = re.sub(
283
+ r"<w:tc[ >](?:(?!<w:tc[ >]).)*?{%\s*hm\s*%}.*?</w:tc[ >]",
284
+ h_merge_tc,
285
+ src_xml,
286
+ flags=re.DOTALL,
287
+ )
288
+
289
+ def clean_tags(m):
290
+ return (
291
+ m.group(0)
292
+ .replace(r"&#8216;", "'")
293
+ .replace("&lt;", "<")
294
+ .replace("&gt;", ">")
295
+ .replace("“", '"')
296
+ .replace("”", '"')
297
+ .replace("‘", "'")
298
+ .replace("’", "'")
299
+ )
300
+
301
+ src_xml = re.sub(r"(?<=\{[\{%])(.*?)(?=[\}%]})", clean_tags, src_xml)
302
+
303
+ return src_xml
304
+
305
+ def render_xml_part(self, src_xml, part, context, jinja_env=None):
306
+ src_xml = re.sub(r"<w:p([ >])", r"\n<w:p\1", src_xml)
307
+ try:
308
+ self.current_rendering_part = part
309
+ if jinja_env:
310
+ template = jinja_env.from_string(src_xml)
311
+ else:
312
+ template = Template(src_xml)
313
+ dst_xml = template.render(context)
314
+ except TemplateError as exc:
315
+ if hasattr(exc, "lineno") and exc.lineno is not None:
316
+ line_number = max(exc.lineno - 4, 0)
317
+ exc.docx_context = map(
318
+ lambda x: re.sub(r"<[^>]+>", "", x),
319
+ src_xml.splitlines()[line_number: (line_number + 7)], # fmt: skip
320
+ )
321
+
322
+ raise exc
323
+ dst_xml = re.sub(r"\n<w:p([ >])", r"<w:p\1", dst_xml)
324
+ dst_xml = (
325
+ dst_xml.replace("{_{", "{{")
326
+ .replace("}_}", "}}")
327
+ .replace("{_%", "{%")
328
+ .replace("%_}", "%}")
329
+ )
330
+ dst_xml = self.resolve_listing(dst_xml)
331
+ return dst_xml
332
+
333
+ def render_properties(
334
+ self, context: Dict[str, Any], jinja_env: Optional[Environment] = None
335
+ ) -> None:
336
+ # List of string attributes of docx.opc.coreprops.CoreProperties which are strings.
337
+ # It seems that some attributes cannot be written as strings. Those are commented out.
338
+ properties = [
339
+ "author",
340
+ # 'category',
341
+ "comments",
342
+ # 'content_status',
343
+ "identifier",
344
+ # 'keywords',
345
+ "language",
346
+ # 'last_modified_by',
347
+ "subject",
348
+ "title",
349
+ # 'version',
350
+ ]
351
+ if jinja_env is None:
352
+ jinja_env = Environment()
353
+
354
+ for prop in properties:
355
+ initial = getattr(self.docx.core_properties, prop)
356
+ template = jinja_env.from_string(initial)
357
+ rendered = template.render(context)
358
+ setattr(self.docx.core_properties, prop, rendered)
359
+
360
+ def render_footnotes(
361
+ self, context: Dict[str, Any], jinja_env: Optional[Environment] = None
362
+ ) -> None:
363
+ if jinja_env is None:
364
+ jinja_env = Environment()
365
+
366
+ for section in self.docx.sections:
367
+ for part in section.part.package.parts:
368
+ if part.content_type == (
369
+ "application/vnd.openxmlformats-officedocument"
370
+ ".wordprocessingml.footnotes+xml"
371
+ ):
372
+ xml = self.patch_xml(
373
+ part.blob.decode("utf-8")
374
+ if isinstance(part.blob, bytes)
375
+ else part.blob
376
+ )
377
+ xml = self.render_xml_part(xml, part, context, jinja_env)
378
+ part._blob = xml.encode("utf-8")
379
+
380
+ def resolve_listing(self, xml):
381
+
382
+ def resolve_text(run_properties, paragraph_properties, m):
383
+ xml = m.group(0).replace(
384
+ "\t",
385
+ "</w:t></w:r>"
386
+ "<w:r>%s<w:tab/></w:r>"
387
+ '<w:r>%s<w:t xml:space="preserve">' % (run_properties, run_properties),
388
+ )
389
+ xml = xml.replace(
390
+ "\a",
391
+ "</w:t></w:r></w:p>"
392
+ '<w:p>%s<w:r>%s<w:t xml:space="preserve">'
393
+ % (paragraph_properties, run_properties),
394
+ )
395
+ xml = xml.replace("\n", '</w:t><w:br/><w:t xml:space="preserve">')
396
+ xml = xml.replace(
397
+ "\f",
398
+ "</w:t></w:r></w:p>"
399
+ '<w:p><w:r><w:br w:type="page"/></w:r></w:p>'
400
+ '<w:p>%s<w:r>%s<w:t xml:space="preserve">'
401
+ % (paragraph_properties, run_properties),
402
+ )
403
+ return xml
404
+
405
+ def resolve_run(paragraph_properties, m):
406
+ run_properties = re.search(r"<w:rPr>.*?</w:rPr>", m.group(0))
407
+ run_properties = run_properties.group(0) if run_properties else ""
408
+ return re.sub(
409
+ r"<w:t(?: [^>]*)?>.*?</w:t>",
410
+ lambda x: resolve_text(run_properties, paragraph_properties, x),
411
+ m.group(0),
412
+ flags=re.DOTALL,
413
+ )
414
+
415
+ def resolve_paragraph(m):
416
+ paragraph_properties = re.search(r"<w:pPr>.*?</w:pPr>", m.group(0))
417
+ paragraph_properties = (
418
+ paragraph_properties.group(0) if paragraph_properties else ""
419
+ )
420
+ return re.sub(
421
+ r"<w:r(?: [^>]*)?>.*?</w:r>",
422
+ lambda x: resolve_run(paragraph_properties, x),
423
+ m.group(0),
424
+ flags=re.DOTALL,
425
+ )
426
+
427
+ xml = re.sub(
428
+ r"<w:p(?: [^>]*)?>.*?</w:p>", resolve_paragraph, xml, flags=re.DOTALL
429
+ )
430
+
431
+ return xml
432
+
433
+ def build_xml(self, context, jinja_env=None):
434
+ xml = self.get_xml()
435
+ xml = self.patch_xml(xml)
436
+ xml = self.render_xml_part(xml, self.docx._part, context, jinja_env)
437
+ return xml
438
+
439
+ def map_tree(self, tree):
440
+ root = self.docx._element
441
+ body = root.body
442
+ root.replace(body, tree)
443
+
444
+ def get_headers_footers(self, uri):
445
+ for relKey, val in self.docx._part.rels.items():
446
+ if (val.reltype == uri) and (val.target_part.blob):
447
+ yield relKey, val.target_part
448
+
449
+ def get_part_xml(self, part):
450
+ return self.xml_to_string(parse_xml(part.blob))
451
+
452
+ def get_headers_footers_encoding(self, xml):
453
+ m = re.match(r'<\?xml[^\?]+\bencoding="([^"]+)"', xml, re.I)
454
+ if m:
455
+ return m.group(1)
456
+ return "utf-8"
457
+
458
+ def build_headers_footers_xml(self, context, uri, jinja_env=None):
459
+ for relKey, part in self.get_headers_footers(uri):
460
+ xml = self.get_part_xml(part)
461
+ encoding = self.get_headers_footers_encoding(xml)
462
+ xml = self.patch_xml(xml)
463
+ xml = self.render_xml_part(xml, part, context, jinja_env)
464
+ yield relKey, xml.encode(encoding)
465
+
466
+ def map_headers_footers_xml(self, relKey, xml):
467
+ part = self.docx._part.rels[relKey].target_part
468
+ new_part = XmlPart.load(part.partname, part.content_type, xml, part.package)
469
+ for rId, rel in part.rels.items():
470
+ new_part.load_rel(rel.reltype, rel._target, rel.rId, rel.is_external)
471
+ self.docx._part.rels[relKey]._target = new_part
472
+
473
+ def render(
474
+ self,
475
+ context: Dict[str, Any],
476
+ jinja_env: Optional[Environment] = None,
477
+ autoescape: bool = False,
478
+ ) -> None:
479
+ # init template working attributes
480
+ self.render_init()
481
+
482
+ if autoescape:
483
+ if not jinja_env:
484
+ jinja_env = Environment(autoescape=autoescape)
485
+ else:
486
+ jinja_env.autoescape = autoescape
487
+
488
+ # Body
489
+ xml_src = self.build_xml(context, jinja_env)
490
+
491
+ # fix tables if needed
492
+ tree = self.fix_tables(xml_src)
493
+
494
+ # fix docPr ID's
495
+ self.fix_docpr_ids(tree)
496
+
497
+ # Replace body xml tree
498
+ self.map_tree(tree)
499
+
500
+ # Headers
501
+ headers = self.build_headers_footers_xml(context, self.HEADER_URI, jinja_env)
502
+ for relKey, xml in headers:
503
+ self.map_headers_footers_xml(relKey, xml)
504
+
505
+ # Footers
506
+ footers = self.build_headers_footers_xml(context, self.FOOTER_URI, jinja_env)
507
+ for relKey, xml in footers:
508
+ self.map_headers_footers_xml(relKey, xml)
509
+
510
+ self.render_properties(context, jinja_env)
511
+
512
+ self.render_footnotes(context, jinja_env)
513
+
514
+ # set rendered flag
515
+ self.is_rendered = True
516
+
517
+ # using of TC tag in for cycle can cause that count of columns does not
518
+ # correspond to real count of columns in row. This function is able to fix it.
519
+ def fix_tables(self, xml):
520
+ parser = etree.XMLParser(recover=True)
521
+ tree = etree.fromstring(xml, parser=parser)
522
+ # get namespace
523
+ ns = "{" + tree.nsmap["w"] + "}"
524
+ # walk trough xml and find table
525
+ for t in tree.iter(ns + "tbl"):
526
+ tblGrid = t.find(ns + "tblGrid")
527
+ columns = tblGrid.findall(ns + "gridCol")
528
+ to_add = 0
529
+ # walk trough all rows and try to find if there is higher cell count
530
+ for r in t.iter(ns + "tr"):
531
+ cells = r.findall(ns + "tc")
532
+ if (len(columns) + to_add) < len(cells):
533
+ to_add = len(cells) - len(columns)
534
+ # is necessary to add columns?
535
+ if to_add > 0:
536
+ # at first, calculate width of table according to columns
537
+ # (we want to preserve it)
538
+ width = 0.0
539
+ new_average = None
540
+ for c in columns:
541
+ if c.get(ns + "w") is not None:
542
+ width += float(c.get(ns + "w"))
543
+ # try to keep proportion of table
544
+ if width > 0:
545
+ old_average = width / len(columns)
546
+ new_average = width / (len(columns) + to_add)
547
+ # scale the old columns
548
+ for c in columns:
549
+ c.set(
550
+ ns + "w",
551
+ str(
552
+ int(float(c.get(ns + "w")) * new_average / old_average)
553
+ ),
554
+ )
555
+ # add new columns
556
+ for i in range(to_add):
557
+ etree.SubElement(
558
+ tblGrid, ns + "gridCol", {ns + "w": str(int(new_average))}
559
+ )
560
+
561
+ # Refetch columns after columns addition.
562
+ columns = tblGrid.findall(ns + "gridCol")
563
+ columns_len = len(columns)
564
+
565
+ cells_len_max = 0
566
+
567
+ def get_cell_len(total, cell):
568
+ tc_pr = cell.find(ns + "tcPr")
569
+ grid_span = None if tc_pr is None else tc_pr.find(ns + "gridSpan")
570
+
571
+ if grid_span is not None:
572
+ return total + int(grid_span.get(ns + "val"))
573
+
574
+ return total + 1
575
+
576
+ # Calculate max of table cells to compare with `gridCol`.
577
+ for r in t.iter(ns + "tr"):
578
+ cells = r.findall(ns + "tc")
579
+ cells_len = functools.reduce(get_cell_len, cells, 0)
580
+ cells_len_max = max(cells_len_max, cells_len)
581
+
582
+ to_remove = columns_len - cells_len_max
583
+
584
+ # If after the loop, there're less columns, than
585
+ # originally was, remove extra `gridCol` declarations.
586
+ if to_remove > 0:
587
+ # Have to keep track of the removed width to scale the
588
+ # table back to its original width.
589
+ removed_width = 0.0
590
+
591
+ for c in columns[-to_remove:]:
592
+ removed_width += float(c.get(ns + "w"))
593
+
594
+ tblGrid.remove(c)
595
+
596
+ columns_left = tblGrid.findall(ns + "gridCol")
597
+
598
+ # Distribute `removed_width` across all columns that has
599
+ # left after extras removal.
600
+ extra_space = 0
601
+ if len(columns_left) > 0:
602
+ extra_space = removed_width / len(columns_left)
603
+ extra_space = int(extra_space)
604
+
605
+ for c in columns_left:
606
+ c.set(ns + "w", str(int(float(c.get(ns + "w")) + extra_space)))
607
+
608
+ return tree
609
+
610
+ def fix_docpr_ids(self, tree):
611
+ # some Ids may have some collisions : so renumbering all of them :
612
+ for elt in tree.xpath("//wp:docPr", namespaces=docx.oxml.ns.nsmap):
613
+ self.docx_ids_index += 1
614
+ elt.attrib["id"] = str(self.docx_ids_index)
615
+
616
+ def new_subdoc(self, docpath=None) -> Subdoc:
617
+ from .subdoc import Subdoc
618
+
619
+ self.init_docx()
620
+ return Subdoc(self, docpath)
621
+
622
+ @staticmethod
623
+ def get_file_crc(file_obj):
624
+ if hasattr(file_obj, "read"):
625
+ buf = file_obj.read()
626
+ else:
627
+ with open(file_obj, "rb") as fh:
628
+ buf = fh.read()
629
+
630
+ crc = binascii.crc32(buf) & 0xFFFFFFFF
631
+ return crc
632
+
633
+ def replace_media(self, src_file, dst_file):
634
+ """Replace one media by another one into a docx
635
+
636
+ This has been done mainly because it is not possible to add images in
637
+ docx header/footer.
638
+ With this function, put a dummy picture in your header/footer,
639
+ then specify it with its replacement in this function using the file path
640
+ or file-like objects.
641
+
642
+ Syntax: tpl.replace_media('dummy_media_to_replace.png','media_to_paste.jpg')
643
+ -- or --
644
+ tpl.replace_media(io.BytesIO(image_stream), io.BytesIO(new_image_stream))
645
+
646
+ Note: for images, the aspect ratio will be the same as the replaced image
647
+
648
+ Note2: it is important to have the source media file as it is required
649
+ to calculate its CRC to find them in the docx
650
+ """
651
+
652
+ crc = self.get_file_crc(src_file)
653
+ if hasattr(dst_file, "read"):
654
+ self.crc_to_new_media[crc] = dst_file.read()
655
+ else:
656
+ with open(dst_file, "rb") as fh:
657
+ self.crc_to_new_media[crc] = fh.read()
658
+
659
+ def replace_pic(self, embedded_file, dst_file):
660
+ """Replace embedded picture with original-name given by embedded_file.
661
+ (give only the file basename, not the full path)
662
+ The new picture is given by dst_file (either a filename or a file-like
663
+ object)
664
+
665
+ Notes:
666
+ 1) embedded_file and dst_file must have the same extension/format
667
+ in case dst_file is a file-like object, no check is done on
668
+ format compatibility
669
+ 2) the aspect ratio will be the same as the replaced image
670
+ 3) There is no need to keep the original file (this is not the case
671
+ for replace_embedded and replace_media)
672
+ """
673
+
674
+ if hasattr(dst_file, "read"):
675
+ # NOTE: file extension not checked
676
+ self.pics_to_replace[embedded_file] = dst_file.read()
677
+ else:
678
+ with open(dst_file, "rb") as fh:
679
+ self.pics_to_replace[embedded_file] = fh.read()
680
+
681
+ def replace_embedded(self, src_file, dst_file):
682
+ """Replace one embedded object by another one into a docx
683
+
684
+ This has been done mainly because it is not possible to add images
685
+ in docx header/footer.
686
+ With this function, put a dummy picture in your header/footer,
687
+ then specify it with its replacement in this function
688
+
689
+ Syntax: tpl.replace_embedded('dummy_doc.docx','doc_to_paste.docx')
690
+
691
+ Note2 : it is important to have the source file as it is required to
692
+ calculate its CRC to find them in the docx
693
+ """
694
+ with open(dst_file, "rb") as fh:
695
+ crc = self.get_file_crc(src_file)
696
+ self.crc_to_new_embedded[crc] = fh.read()
697
+
698
+ def replace_zipname(self, zipname, dst_file):
699
+ """Replace one file in the docx file
700
+
701
+ First note that a MSWord .docx file is in fact a zip file.
702
+
703
+ This method can be used to replace document embedded in the docx template.
704
+
705
+ Some embedded document may have been modified by MSWord while saving
706
+ the template : thus replace_embedded() cannot be used as CRC is not the
707
+ same as the original file.
708
+
709
+ This method works for embedded MSWord file like Excel or PowerPoint file,
710
+ but won't work for others like PDF, Python or even Text files :
711
+ For these ones, MSWord generate an oleObjectNNN.bin file which is no
712
+ use to be replaced as it is encoded.
713
+
714
+ Syntax:
715
+
716
+ tpl.replace_zipname(
717
+ 'word/embeddings/Feuille_Microsoft_Office_Excel1.xlsx',
718
+ 'my_excel_file.xlsx')
719
+
720
+ The zipname is the one you can find when you open docx with WinZip,
721
+ 7zip (Windows) or unzip -l (Linux). The zipname starts with
722
+ "word/embeddings/". Note that the file is renamed by MSWord,
723
+ so you have to guess a little bit...
724
+ """
725
+ with open(dst_file, "rb") as fh:
726
+ self.zipname_to_replace[zipname] = fh.read()
727
+
728
+ def reset_replacements(self):
729
+ """Reset replacement dictionaries
730
+
731
+ This will reset data for image/embedded/zipname replacement
732
+
733
+ This is useful when calling several times render() with different
734
+ image/embedded/zipname replacements without re-instantiating
735
+ DocxTemplate object.
736
+ In this case, the right sequence for each rendering will be :
737
+ - reset_replacements(...)
738
+ - replace_zipname(...), replace_media(...) and/or replace_embedded(...),
739
+ - render(...)
740
+
741
+ If you instantiate DocxTemplate object before each render(),
742
+ this method is useless.
743
+ """
744
+ self.crc_to_new_media = {}
745
+ self.crc_to_new_embedded = {}
746
+ self.zipname_to_replace = {}
747
+ self.pics_to_replace = {}
748
+
749
+ def post_processing(self, docx_file):
750
+ if self.crc_to_new_media or self.crc_to_new_embedded or self.zipname_to_replace:
751
+
752
+ if hasattr(docx_file, "read"):
753
+ tmp_file = io.BytesIO()
754
+ DocxTemplate(docx_file).save(tmp_file)
755
+ tmp_file.seek(0)
756
+ docx_file.seek(0)
757
+ docx_file.truncate()
758
+ docx_file.seek(0)
759
+
760
+ else:
761
+ tmp_file = "%s_docform_before_replace_medias" % docx_file
762
+ os.rename(docx_file, tmp_file)
763
+
764
+ with zipfile.ZipFile(tmp_file) as zin:
765
+ with zipfile.ZipFile(docx_file, "w") as zout:
766
+ for item in zin.infolist():
767
+ buf = zin.read(item.filename)
768
+ if item.filename in self.zipname_to_replace:
769
+ zout.writestr(item, self.zipname_to_replace[item.filename])
770
+ elif (
771
+ item.filename.startswith("word/media/")
772
+ and item.CRC in self.crc_to_new_media
773
+ ):
774
+ zout.writestr(item, self.crc_to_new_media[item.CRC])
775
+ elif (
776
+ item.filename.startswith("word/embeddings/")
777
+ and item.CRC in self.crc_to_new_embedded
778
+ ):
779
+ zout.writestr(item, self.crc_to_new_embedded[item.CRC])
780
+ else:
781
+ zout.writestr(item, buf)
782
+
783
+ if not hasattr(tmp_file, "read"):
784
+ os.remove(tmp_file)
785
+ if hasattr(docx_file, "read"):
786
+ docx_file.seek(0)
787
+
788
+ def pre_processing(self):
789
+
790
+ if self.pics_to_replace:
791
+ self._replace_pics()
792
+
793
+ def _replace_pics(self):
794
+ """Replaces pictures xml tags in the docx template with pictures provided by the user"""
795
+
796
+ replaced_pics = {key: False for key in self.pics_to_replace}
797
+
798
+ # Main document
799
+ part = self.docx.part
800
+ self._replace_docx_part_pics(part, replaced_pics)
801
+
802
+ # Header/Footer
803
+ for relid, rel in part.rels.items():
804
+ if rel.reltype in (REL_TYPE.HEADER, REL_TYPE.FOOTER):
805
+ self._replace_docx_part_pics(rel.target_part, replaced_pics)
806
+
807
+ if not self.allow_missing_pics:
808
+ # make sure all template images defined by user were replaced
809
+ for img_id, replaced in replaced_pics.items():
810
+ if not replaced:
811
+ raise ValueError(
812
+ "Picture %s not found in the docx template" % img_id
813
+ )
814
+
815
+ def get_pic_map(self):
816
+ return self.pic_map
817
+
818
+ def _replace_docx_part_pics(self, doc_part, replaced_pics):
819
+
820
+ et = etree.fromstring(doc_part.blob)
821
+
822
+ part_map = {}
823
+
824
+ gds = et.xpath("//a:graphic/a:graphicData", namespaces=docx.oxml.ns.nsmap)
825
+ for gd in gds:
826
+ rel = None
827
+ # Either IMAGE, CHART, SMART_ART, ...
828
+ try:
829
+ if gd.attrib["uri"] == docx.oxml.ns.nsmap["pic"]:
830
+ # Either PICTURE or LINKED_PICTURE image
831
+ blip = gd.xpath(
832
+ "pic:pic/pic:blipFill/a:blip", namespaces=docx.oxml.ns.nsmap
833
+ )[0]
834
+ dest = blip.xpath("@r:embed", namespaces=docx.oxml.ns.nsmap)
835
+ if len(dest) > 0:
836
+ rel = dest[0]
837
+ else:
838
+ continue
839
+ else:
840
+ continue
841
+
842
+ non_visual_properties = "pic:pic/pic:nvPicPr/pic:cNvPr/"
843
+ filename = gd.xpath(
844
+ "%s@name" % non_visual_properties, namespaces=docx.oxml.ns.nsmap
845
+ )[0]
846
+ titles = gd.xpath(
847
+ "%s@title" % non_visual_properties, namespaces=docx.oxml.ns.nsmap
848
+ )
849
+ if titles:
850
+ title = titles[0]
851
+ else:
852
+ title = ""
853
+ descriptions = gd.xpath(
854
+ "%s@descr" % non_visual_properties, namespaces=docx.oxml.ns.nsmap
855
+ )
856
+ if descriptions:
857
+ description = descriptions[0]
858
+ else:
859
+ description = ""
860
+
861
+ part_map[filename] = (
862
+ doc_part.rels[rel].target_ref,
863
+ doc_part.rels[rel].target_part,
864
+ )
865
+
866
+ # replace data
867
+ for img_id, img_data in self.pics_to_replace.items():
868
+ if img_id == filename or img_id == title or img_id == description:
869
+ part_map[filename][1]._blob = img_data
870
+ replaced_pics[img_id] = True
871
+ break
872
+
873
+ # FIXME: figure out what exceptions are thrown here
874
+ # and catch more specific exceptions
875
+ except Exception:
876
+ continue
877
+
878
+ self.pic_map.update(part_map)
879
+
880
+ def build_url_id(self, url):
881
+ self.init_docx()
882
+ return self.docx._part.relate_to(url, REL_TYPE.HYPERLINK, is_external=True)
883
+
884
+ def save(self, filename: Union[IO[bytes], str, PathLike], *args, **kwargs) -> None:
885
+ # case where save() is called without doing rendering
886
+ # ( user wants only to replace image/embedded/zipname )
887
+ if not self.is_saved and not self.is_rendered:
888
+ self.docx = Document(self.template_file)
889
+ self.pre_processing()
890
+ self.docx.save(filename, *args, **kwargs)
891
+ self.post_processing(filename)
892
+ self.is_saved = True
893
+
894
+ def get_undeclared_template_variables(
895
+ self,
896
+ jinja_env: Optional[Environment] = None,
897
+ context: Optional[Dict[str, Any]] = None,
898
+ ) -> Set[str]:
899
+ # Create a temporary document to analyze the template without affecting the current state
900
+ temp_doc = Document(self.template_file)
901
+
902
+ # Get XML from the temporary document
903
+ xml = self.xml_to_string(temp_doc._element.body)
904
+ xml = self.patch_xml(xml)
905
+
906
+ # Add headers and footers
907
+ for uri in [self.HEADER_URI, self.FOOTER_URI]:
908
+ for relKey, val in temp_doc._part.rels.items():
909
+ if (val.reltype == uri) and (val.target_part.blob):
910
+ _xml = self.xml_to_string(parse_xml(val.target_part.blob))
911
+ xml += self.patch_xml(_xml)
912
+
913
+ if jinja_env:
914
+ env = jinja_env
915
+ else:
916
+ env = Environment()
917
+
918
+ parse_content = env.parse(xml)
919
+ all_variables = meta.find_undeclared_variables(parse_content)
920
+
921
+ # If context is provided, return only variables that are not in the context
922
+ if context is not None:
923
+ provided_variables = set(context.keys())
924
+ return all_variables - provided_variables
925
+
926
+ # If no context provided, return all variables (original behavior)
927
+ return all_variables