Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Monkey-patch Document to accept a Word Template .dotx - tested on python-docx v0.8.10
# Monkey-patch Document to load a Word Template .dotx
# tested on python-docx v0.8.10 and based on https://github.com/python-openxml/python-docx/issues/363
import docx
from docx.opc.constants import CONTENT_TYPE
from docx.package import Package
from docx.api import _default_docx_path
from docx.opc.part import PartFactory
from docx.parts.document import DocumentPart
CONTENT_TYPE.WML_DOCUMENT_TEMPLATE = 'application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml'
def DocumentOrTemplate(docx=None):
"""
Return a |Document| object loaded from *docx*, where *docx* can be
either a path to a ``.docx`` file (a string) or a file-like object. If
*docx* is missing or ``None``, the built-in default document "template"
is loaded.
"""
docx = _default_docx_path() if docx is None else docx
document_part = Package.open(docx).main_document_part
if document_part.content_type == CONTENT_TYPE.WML_DOCUMENT_TEMPLATE:
# change it back to a document so we can save it later
document_part._content_type = CONTENT_TYPE.WML_DOCUMENT
elif document_part.content_type != CONTENT_TYPE.WML_DOCUMENT_MAIN:
tmpl = "file '%s' is not a Word file, content type is '%s'"
raise ValueError(tmpl % (docx, document_part.content_type))
return document_part.document
docx.Document = DocumentOrTemplate
PartFactory.part_type_for[CONTENT_TYPE.WML_DOCUMENT_TEMPLATE] = DocumentPart
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.