From a3efa3356859a1ce54adb790c42c5c8f1e4e9343 Mon Sep 17 00:00:00 2001 From: Srinivas Chippagiri Date: Wed, 25 Nov 2026 09:30:30 -0800 Subject: [PATCH] Give shapes and text boxes in a loop their own ids fix_docpr_ids() renumbers wp:docPr, but a shape or text box also has an anchorId and a VML fallback with its own id and o:spid. A loop copied them as is, so the copies clashed and Word reported the file as corrupted. Copies now get new unique ids; the first one keeps the ids from the template, and an OLE object's ShapeID follows its shape. Fixes #22 --- docform/docx/template.py | 60 +++++++++++++++++++++++++++++++++++++++ tests/unit/test_render.py | 56 ++++++++++++++++++++++++++++++++++++ 2 files changed, 116 insertions(+) diff --git a/docform/docx/template.py b/docform/docx/template.py index cbaed24..2111b6a 100644 --- a/docform/docx/template.py +++ b/docform/docx/template.py @@ -855,6 +855,7 @@ def render( # fix docPr ID's self.fix_docpr_ids(tree) + self.fix_shape_ids(tree) # Replace body xml tree self.drop_duplicate_bookmarks(tree) @@ -1070,6 +1071,65 @@ def fix_docpr_ids(self, tree): self.docx_ids_index += 1 elt.attrib["id"] = str(self.docx_ids_index) + SHAPE_ANCHOR_IDS = ( + "{http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing}anchorId", + "{http://schemas.microsoft.com/office/word/2010/wordml}anchorId", + ) + VML_SHAPE = "{urn:schemas-microsoft-com:vml}shape" + VML_SPID = "{urn:schemas-microsoft-com:office:office}spid" + OLE_OBJECT = "{urn:schemas-microsoft-com:office:office}OLEObject" + + def fix_shape_ids(self, tree): + """Give copies of a shape or text box their own ids. + + A loop repeats a shape's anchorId and its VML fallback's id and + o:spid, and Word reports such a document as corrupted. The first + copy keeps its ids, later copies get new unique ones. + """ + elements = [el for el in tree.iter() if isinstance(el.tag, str)] + + def dedupe(items, get, put, make): + used = {get(el) for el in items} + seen = set() + index = 1 + for el in items: + value = get(el) + if value not in seen: + seen.add(value) + continue + while make(index) in used: + index += 1 + new = make(index) + used.add(new) + put(el, value, new) + + for attr in self.SHAPE_ANCHOR_IDS: + dedupe( + [el for el in elements if el.get(attr) is not None], + lambda el, a=attr: el.get(a).upper(), + lambda el, old, new, a=attr: el.set(a, new), + lambda index: "%08X" % (0x10000000 + index), + ) + + shapes = [ + el for el in elements if el.tag == self.VML_SHAPE and el.get("id") is not None + ] + + def set_shape_id(shape, old, new): + shape.set("id", new) + parent = shape.getparent() + for ole in [] if parent is None else parent.iter(self.OLE_OBJECT): + if ole.get("ShapeID") == old: + ole.set("ShapeID", new) + + dedupe(shapes, lambda el: el.get("id"), set_shape_id, lambda i: "_x0000_s%d" % (3000 + i)) + dedupe( + [el for el in shapes if el.get(self.VML_SPID) is not None], + lambda el: el.get(self.VML_SPID), + lambda el, old, new: el.set(self.VML_SPID, new), + lambda index: "_x0000_s%d" % (4000 + index), + ) + def new_subdoc(self, docpath=None) -> Subdoc: try: from .subdoc import Subdoc diff --git a/tests/unit/test_render.py b/tests/unit/test_render.py index 10a0831..e520bba 100644 --- a/tests/unit/test_render.py +++ b/tests/unit/test_render.py @@ -707,3 +707,59 @@ def test_richtext_carriage_return_becomes_line_break(make_docx): tpl = DocxTemplate(make_docx(["{{r rt }}"])) tpl.render({"rt": RichText("a\r\nb\rc", bold=True)}) assert saved(tpl).paragraphs[0]._p.xml.count("") == 2 + + +TEXT_BOX_XML = ( + '' + '' + '' + '' + '0' + '0' + '' + '' + '' + '' + 'box' + '' + '' + '' + 'box' + '' +) + + +def test_text_box_in_loop_gets_unique_ids(tmp_path): + from docx.oxml import parse_xml + + doc = Document() + doc.add_paragraph("{%p for x in xs %}") + doc.add_paragraph()._p.append(parse_xml(TEXT_BOX_XML)) + doc.add_paragraph("{%p endfor %}") + path = tmp_path / "textbox.docx" + doc.save(str(path)) + + tpl = DocxTemplate(str(path)) + tpl.render({"xs": [1, 2, 3]}) + body = saved(tpl).element.body + ns = { + "wp": "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing", + "wp14": "http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing", + "v": "urn:schemas-microsoft-com:vml", + "o": "urn:schemas-microsoft-com:office:office", + } + for path_ in (".//wp:anchor/@wp14:anchorId", ".//v:shape/@id", ".//v:shape/@o:spid", ".//wp:docPr/@id"): + values = etree._Element.xpath(body, path_, namespaces=ns) + assert len(values) == 3, path_ + assert len(set(values)) == 3, (path_, values) + # the first copy keeps the ids from the template + assert etree._Element.xpath(body, "(.//v:shape)[1]/@o:spid", namespaces=ns) == ["_x0000_s1026"]