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
2 changes: 2 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ Unreleased
properties like ``w:textAlignment``, and ``{%-``/``-%}`` next to a table no longer drop its tags.
- Templates saved by LibreOffice no longer get a second ``docProps/core.xml``, which made
LibreOffice refuse the generated file.
- A subdoc that ends with a table gets an empty paragraph after it, so ``{{p subdoc }}`` at the
end of the document or of a table cell no longer makes Word reject the file.

0.21.0 (2026-11-15)
-------------------
Expand Down
4 changes: 4 additions & 0 deletions docform/docx/subdoc.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,10 @@ def _get_xml(self):
wrapper = etree.Element(destination_body.tag, nsmap=destination_body.nsmap)
for element in body:
wrapper.append(deepcopy(element))
# Word needs a paragraph after a table at the end of a cell or of the
# document, and {{p subdoc }} can put the subdoc's last table there.
if wrapper[-1].tag == "{%s}tbl" % nsmap["w"]:
etree.SubElement(wrapper, "{%s}p" % nsmap["w"])

xml = etree.tostring(wrapper, encoding="unicode", pretty_print=False)
return xml.partition(">")[2].rpartition("</")[0]
Expand Down
21 changes: 21 additions & 0 deletions tests/unit/test_objects.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,3 +179,24 @@ def test_replace_pic_drops_the_unused_image(tmp_path):
assert pics == {"only": other}
images = [p for p in part.related_parts.values() if p.content_type.startswith("image/")]
assert len(images) == 1


def test_subdoc_ending_with_a_table_is_followed_by_a_paragraph(tmp_path):
pytest.importorskip("docxcompose")
doc = Document()
doc.add_table(rows=1, cols=1).cell(0, 0).text = "{{p sd }}"
doc.add_paragraph("{{p sd }}")
path = tmp_path / "tpl.docx"
doc.save(str(path))

tpl = DocxTemplate(str(path))
sd = tpl.new_subdoc()
sd.add_table(rows=1, cols=1).cell(0, 0).text = "inner"
tpl.render({"sd": sd})
body = saved(tpl).element.body

# A table cell has to end with a paragraph, and so does the body
# before its section properties.
outer_cell = body.xpath("./w:tbl/w:tr/w:tc")[0]
assert outer_cell[-1].tag.endswith("}p")
assert body[-2].tag.endswith("}p")
Loading