Skip to content

Instantly share code, notes, and snippets.

@adejones
Last active April 16, 2019 16:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adejones/309e7c23cdbda9c7be480133925acb73 to your computer and use it in GitHub Desktop.
Save adejones/309e7c23cdbda9c7be480133925acb73 to your computer and use it in GitHub Desktop.
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