Last active
April 16, 2019 16:40
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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