Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 27 additions & 1 deletion docform/docx/template.py
Original file line number Diff line number Diff line change
Expand Up @@ -812,6 +812,8 @@ def build_headers_footers_xml(self, context, uri, jinja_env=None):
def map_headers_footers_xml(self, relKey, xml):
part = self.docx._part.rels[relKey].target_part
new_part = XmlPart.load(part.partname, part.content_type, xml, part.package)
# keep numbering after the body so a header logo can't reuse an id
self.fix_docpr_ids(new_part.element)
for rId, rel in part.rels.items():
new_part.load_rel(rel.reltype, rel._target, rel.rId, rel.is_external)
self.docx._part.rels[relKey]._target = new_part
Expand Down Expand Up @@ -886,6 +888,7 @@ def render(
self.render_properties(context, jinja_env)

self.render_footnotes(context, jinja_env)
self.fix_footnotes_docpr_ids()
self.drop_unreferenced_notes()

# set rendered flag
Expand Down Expand Up @@ -1079,10 +1082,33 @@ def fix_cell_properties(self, tree):

def fix_docpr_ids(self, tree):
# some Ids may have some collisions : so renumbering all of them :
for elt in tree.xpath("//wp:docPr", namespaces=docx.oxml.ns.nsmap):
# iter() rather than xpath(): python-docx elements override xpath()
# and it doesn't take a namespaces argument there
for elt in tree.iter("{%s}docPr" % docx.oxml.ns.nsmap["wp"]):
self.docx_ids_index += 1
elt.attrib["id"] = str(self.docx_ids_index)

def fix_footnotes_docpr_ids(self):
"""Renumber drawings in footnotes after the body, headers and footers.

Drawing ids have to be unique across the whole document, not just
within one part, so this keeps counting from where the others ended.
"""
for part in self.docx.part.package.iter_parts():
if part.content_type != self.FOOTNOTES_CONTENT_TYPE:
continue
blob = part.blob
if b"docPr" not in blob:
continue
try:
tree = etree.fromstring(blob)
except etree.XMLSyntaxError:
continue
self.fix_docpr_ids(tree)
part._blob = etree.tostring(
tree, encoding="UTF-8", xml_declaration=True, standalone=True
)

SHAPE_ANCHOR_IDS = (
"{http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing}anchorId",
"{http://schemas.microsoft.com/office/word/2010/wordml}anchorId",
Expand Down
97 changes: 97 additions & 0 deletions tests/unit/test_objects.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import io
from pathlib import Path
import re
import struct
import zipfile
import zlib

import pytest
Expand Down Expand Up @@ -181,6 +183,101 @@ def test_inline_images_get_unique_ids(make_docx):
assert len(set(ids)) == 3


def _docpr_ids(tpl):
"""All wp:docPr ids in every part of the saved document."""
buf = io.BytesIO()
tpl.save(buf)
ids = []
with zipfile.ZipFile(buf) as z:
for name in z.namelist():
if name.startswith("word/") and name.endswith(".xml"):
ids += re.findall(rb'<wp:docPr[^>]*\bid="(\d+)"', z.read(name))
return ids


def _png_file(tmp_path):
path = tmp_path / "logo.png"
path.write_bytes(PNG)
return str(path)


def test_header_logos_and_body_images_get_unique_ids(tmp_path):
png = _png_file(tmp_path)
doc = Document()
section = doc.sections[0]
section.different_first_page_header_footer = True
section.header.paragraphs[0].add_run().add_picture(png, width=Mm(5))
section.first_page_header.paragraphs[0].add_run().add_picture(png, width=Mm(5))
section.footer.paragraphs[0].add_run().add_picture(png, width=Mm(5))
doc.add_paragraph().add_run().add_picture(png, width=Mm(5))
path = tmp_path / "logos.docx"
doc.save(str(path))

tpl = DocxTemplate(path)
tpl.render({})
ids = _docpr_ids(tpl)
assert len(ids) == 4
assert len(set(ids)) == 4


def test_images_in_header_loop_get_unique_ids(make_docx):
tpl = DocxTemplate(
make_docx(["{{ evidence }}"], header="{% for i in logos %}{{ i }}{% endfor %}")
)
tpl.render({
"logos": [InlineImage(tpl, io.BytesIO(PNG)) for _ in range(3)],
"evidence": InlineImage(tpl, io.BytesIO(PNG)),
})
ids = _docpr_ids(tpl)
assert len(ids) == 4
assert len(set(ids)) == 4


def test_header_image_id_does_not_clash_with_renumbered_body(tmp_path):
png = _png_file(tmp_path)
doc = Document()
doc.sections[0].header.paragraphs[0].add_run().add_picture(png, width=Mm(5))
# Word numbers drawings across the whole file, so a header image can
# already carry an id the body renumbering is about to hand out.
doc.sections[0].header._element.xpath(".//wp:docPr")[0].set("id", "1001")
doc.add_paragraph().add_run().add_picture(png, width=Mm(5))
path = tmp_path / "clash.docx"
doc.save(str(path))

tpl = DocxTemplate(path)
tpl.render({})
ids = _docpr_ids(tpl)
assert len(ids) == 2
assert len(set(ids)) == 2


def test_footnote_drawing_gets_unique_id(tmp_path):
png = _png_file(tmp_path)
src = Path(__file__).resolve().parents[1] / "templates" / "footnotes_tpl.docx"
path = tmp_path / "footnote.docx"
drawing = (
'<w:r><w:drawing><wp:inline><wp:extent cx="1" cy="1"/>'
'<wp:docPr id="1001" name="Picture 1"/></wp:inline></w:drawing></w:r>'
)
with zipfile.ZipFile(str(src)) as zin, zipfile.ZipFile(str(path), "w") as zout:
for item in zin.infolist():
data = zin.read(item.filename)
if item.filename == "word/footnotes.xml":
text = data.decode("utf-8")
cut = text.rindex("</w:p>")
data = (text[:cut] + drawing + text[cut:]).encode("utf-8")
zout.writestr(item, data)
doc = Document(str(path))
doc.add_paragraph().add_run().add_picture(png, width=Mm(5))
doc.save(str(path))

tpl = DocxTemplate(path)
tpl.render({"a_jinja_variable": "x"})
ids = _docpr_ids(tpl)
assert len(ids) == 2
assert len(set(ids)) == 2


def test_subdoc(make_docx):
pytest.importorskip("docxcompose")
tpl = DocxTemplate(make_docx(["before", "{{p sd }}", "after"]))
Expand Down
15 changes: 15 additions & 0 deletions tests/unit/test_render.py
Original file line number Diff line number Diff line change
Expand Up @@ -661,6 +661,21 @@ def _grid_and_cell_widths(table):
return grid, cells


def test_table_without_grid_still_renders(tmp_path):
doc = Document()
table = doc.add_table(rows=2, cols=2)
table.cell(0, 0).text = "{{ name }}"
table.cell(1, 1).text = "x"
table._tbl.remove(table._tbl.tblGrid)
path = tmp_path / "nogrid.docx"
doc.save(str(path))

tpl = DocxTemplate(path)
tpl.render({"name": "Ada"})
out = saved(tpl)
assert [[c.text for c in r.cells] for r in out.tables[0].rows] == [["Ada", ""], ["", "x"]]


def test_nested_table_does_not_change_outer_grid(tmp_path):
doc = Document()
outer = doc.add_table(rows=1, cols=2)
Expand Down