You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Formatted text after subdoc tag corrupts generated docx (cannot be opened by Microsoft Word) #565
When creating a word with a subdoc tag, if there is some formatted text after the subdoc tag, the generated docx document cannot be opened using Microsoft Word. This can happen simply because some underline is added around the subdoc tag (a simple space underlined seem to be enough to corrupt the resulting document.
It might be caused by a run (the underlined text after the subdoc) being "forcefully" included in the subdoc generated paragraph.
To Reproduce
Attached is the subdoc test found in the library code, slightly modified to add some formatting text around the subdoc tag in the template. The template is the only part that we need to change to see this behaviour. subdoc_corrupted.zip
Expected behavior
The generated document should not be corrupted and Microsoft Word should be able to open it.
Screenshots
Additional context
We cannot always use the {{p subdoc}} syntax because we need some label on the same line. This works fine if there is no underlined text after the tag, but it is easy to add it without being aware and break everything. Since we need to use Microsoft Word to open the files, it is hard to see if the generated docx is corrupted only by using unit tests.
We hit the same issue. In our case the {{clauses}} subdoc tag was inside a paragraph that also contained a <w:bookmarkStart> element — enough context for docxtpl to fail to promote the subdoc to the body level. Instead, all subdoc paragraphs end up as direct children of the surrounding <w:p>, which is invalid OOXML and causes Word to refuse to open the file.
Root cause (what the XML looks like)
After rendering, the problematic paragraph in word/document.xml looks like this:
<!-- template paragraph that held {{clauses}} -->
<w:p>
<w:pPr>...</w:pPr>
<w:bookmarkStart w:id="0" w:name="..."/>
<w:r><w:t/></w:r> <!-- the rendered {{clauses}} tag — now empty -->
<!-- ALL subdoc paragraphs nested inside this one <w:p> — invalid OOXML -->
<w:p><w:r><w:t>Clause 1 text...</w:t></w:r></w:p>
<w:p><w:r><w:t>Clause 2 text...</w:t></w:r></w:p>
...
<w:bookmarkEnd/>
</w:p>
<w:p> nested inside <w:p> is not allowed by the OOXML spec — Word validates this on open and shows a corruption error.
Client-side post-processing workaround
Until the library is fixed, this can be repaired after doc.save() by using lxml to lift the nested paragraphs back up to the <w:body> level:
import zipfile, shutil, random, re
from lxml import etree
_W = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
_PARA_ID_RE = re.compile(r'w14:paraId="[^"]+"')
_TEXT_ID_RE = re.compile(r'w14:textId="[^"]+"')
def _flatten_nested_paragraphs(data: bytes) -> bytes:
"""Lift <w:p> children of <w:p> up to <w:body> level."""
tree = etree.fromstring(data)
body = tree.find(f"{{{_W}}}body")
if body is None:
return data
new_children, modified = [], False
for child in list(body):
if etree.QName(child.tag).localname == "p":
nested = child.findall(f"{{{_W}}}p")
if nested:
modified = True
new_children.extend(nested) # promote nested paras
# drop the outer shell paragraph
else:
new_children.append(child)
else:
new_children.append(child)
if not modified:
return data
for child in list(body):
body.remove(child)
for child in new_children:
body.append(child)
return etree.tostring(tree, xml_declaration=True, encoding="UTF-8", standalone=True)
def fix_docx(docx_path: str) -> None:
"""
Apply after doc.save(). Fixes two issues:
1. Nested <w:p> from the subdoc bug (this issue).
2. Duplicate w14:paraId/textId='77777777' that python-docx emits for
every programmatic paragraph — Word also rejects files with duplicate IDs.
"""
tmp = docx_path + ".fix.tmp"
try:
with zipfile.ZipFile(docx_path, "r") as zin, \
zipfile.ZipFile(tmp, "w", zipfile.ZIP_DEFLATED) as zout:
for item in zin.infolist():
data = zin.read(item.filename)
if item.filename == "word/document.xml":
data = _flatten_nested_paragraphs(data)
content = data.decode("utf-8")
content = _PARA_ID_RE.sub(
lambda _: f'w14:paraId="{random.randint(1, 0xFFFFFFFE):08X}"',
content,
)
content = _TEXT_ID_RE.sub(
lambda _: f'w14:textId="{random.randint(1, 0xFFFFFFFE):08X}"',
content,
)
data = content.encode("utf-8")
zout.writestr(item, data)
shutil.move(tmp, docx_path)
except Exception:
if os.path.exists(tmp):
os.remove(tmp)
raise
Note: the ID deduplication is included because programmatically-added paragraphs all get w14:textId="77777777" from python-docx, which is a second independent reason Word rejects such files. Both issues appear together whenever a subdoc with many paragraphs is rendered.
I reproduced the invalid OOXML with a minimal generated template containing a label, a bookmark, {{ clauses }}, and an underlined trailing space. The subdocument had two paragraphs. After rendering, word/document.xml contained two <w:p> elements inside the placeholder's <w:t> element; that is invalid block content inside a text run and explains why Word rejects the document.
{{p clauses}} avoids embedding the subdocument fragment because it replaces the entire containing paragraph, but that necessarily removes a same-line label and trailing formatting. A safe fix therefore needs an explicit design for inline subdocuments (or validation that rejects this unsupported placement); simply lifting descendant paragraphs after rendering risks losing bookmark/range semantics.
I have not prepared a patch for this yet. Do you prefer a supported transformation that preserves surrounding content, or a clear validation/error for non-standalone subdoc placeholders?
Activity
Spartan1404 commentedon May 8, 2026
Confirming the bug + client-side workaround
We hit the same issue. In our case the {{clauses}} subdoc tag was inside a paragraph that also contained a <w:bookmarkStart> element — enough context for docxtpl to fail to promote the subdoc to the body level. Instead, all subdoc paragraphs end up as direct children of the surrounding <w:p>, which is invalid OOXML and causes Word to refuse to open the file.
Root cause (what the XML looks like)
After rendering, the problematic paragraph in word/document.xml looks like this:
<w:p> nested inside <w:p> is not allowed by the OOXML spec — Word validates this on open and shows a corruption error.
Client-side post-processing workaround
Until the library is fixed, this can be repaired after doc.save() by using lxml to lift the nested paragraphs back up to the <w:body> level:
Note: the ID deduplication is included because programmatically-added paragraphs all get w14:textId="77777777" from python-docx, which is a second independent reason Word rejects such files. Both issues appear together whenever a subdoc with many paragraphs is rendered.
janmarsino98 commentedon Jul 14, 2026
I reproduced the invalid OOXML with a minimal generated template containing a label, a bookmark,
{{ clauses }}, and an underlined trailing space. The subdocument had two paragraphs. After rendering,word/document.xmlcontained two<w:p>elements inside the placeholder's<w:t>element; that is invalid block content inside a text run and explains why Word rejects the document.{{p clauses}}avoids embedding the subdocument fragment because it replaces the entire containing paragraph, but that necessarily removes a same-line label and trailing formatting. A safe fix therefore needs an explicit design for inline subdocuments (or validation that rejects this unsupported placement); simply lifting descendant paragraphs after rendering risks losing bookmark/range semantics.I have not prepared a patch for this yet. Do you prefer a supported transformation that preserves surrounding content, or a clear validation/error for non-standalone subdoc placeholders?
cvas22 commentedon Nov 22, 2026
@ldallolio @Spartan1404 fyi, Docform (the maintained fork at https://github.com/cvas22/docform,
docformon PyPI) now documents that subdocs need{{p mysubdoc }}alone in their paragraph, which avoids the corrupted output. That's in cvas22/docform#180.