diff --git a/docform/docx/subdoc.py b/docform/docx/subdoc.py index 2cfe2e8..041feee 100644 --- a/docform/docx/subdoc.py +++ b/docform/docx/subdoc.py @@ -10,6 +10,7 @@ from docx.document import Document as DocumentObject from docx.oxml import CT_SectPr from docx.oxml.ns import nsmap, qn +from docx.styles import BabelFish from docx.opc.constants import RELATIONSHIP_TYPE as RT from docxcompose.properties import CustomProperties from docxcompose.utils import xpath @@ -29,6 +30,19 @@ nsmap["cp"] = "http://schemas.openxmlformats.org/package/2006/metadata/core-properties" +def _style_ids_and_names(doc): + """Yield (style id, UI name) for each style, like iterating doc.styles.""" + w_name = qn("w:name") + w_val = qn("w:val") + w_style_id = qn("w:styleId") + for style in doc.styles.element.iterchildren(qn("w:style")): + name = style.find(w_name) + name = name.get(w_val) if name is not None else None + if name is not None: + name = BabelFish.internal2ui(name) + yield style.get(w_style_id), name + + class SubdocComposer(Composer): def attach_parts(self, doc, remove_property_fields=True): """Attach docx parts instead of appending the whole document @@ -63,6 +77,15 @@ def attach_parts(self, doc, remove_property_fields=True): self.renumber_nvpicpr_ids() self.fix_section_types(doc) + def _create_style_id_mapping(self, doc): + # Same mapping as docxcompose, read straight from the styles XML. + # Building a python-docx Style object for every style of both + # documents made this most of the time spent per subdoc. + self._style_id2name = dict(_style_ids_and_names(doc)) + self._style_name2id = { + name: style_id for style_id, name in _style_ids_and_names(self.doc) + } + def reset_reference_mapping(self): super().reset_reference_mapping() # style id -> numPr given to the first paragraph of a restarted list @@ -194,13 +217,21 @@ def add_diagrams(self, doc, element): dgm_rel.set("{%s}%s" % (NS["r"], item), new_rid) +def _has_custom_properties(doc): + try: + doc.part.package.part_related_by(RT.CUSTOM_PROPERTIES) + except KeyError: + return False + return True + + class Subdoc(object): """Class for subdocument to insert into master document""" def __init__(self, tpl, docpath=None): self.tpl = tpl self.docx = tpl.get_docx() - self.subdocx = Document(self._as_source(docpath)) + self.subdocx = self._open(docpath) if docpath: compose = SubdocComposer(self.docx) compose.attach_parts(self.subdocx) @@ -208,21 +239,36 @@ def __init__(self, tpl, docpath=None): self.subdocx._part = self.docx._part @staticmethod - def _as_source(docpath): - """Return something Document() can open. - - A python-docx Document or a DocxTemplate (rendered or not) is saved to - memory first, so the subdoc gets its own copy and the object passed in - is left untouched. + def _open(docpath): + """Return the python-docx Document to insert. + + A python-docx Document or a DocxTemplate (rendered or not) is copied, + so the object passed in is left untouched. Building the subdoc only + changes the document body, so copying the body XML is enough and much + faster than saving and reopening the whole package. Custom property + fields can live in headers and footers too, and a DocxTemplate may + have media replacements that only happen on save, so those still go + through a full save. """ from .template import DocxTemplate + if isinstance(docpath, DocxTemplate): + if not ( + docpath.crc_to_new_media + or docpath.crc_to_new_embedded + or docpath.zipname_to_replace + or docpath.pics_to_replace + ): + docpath.init_docx(reload=False) + docpath = docpath.docx + if isinstance(docpath, DocumentObject) and not _has_custom_properties(docpath): + return DocumentObject(deepcopy(docpath.element), docpath.part) if isinstance(docpath, (DocumentObject, DocxTemplate)): stream = io.BytesIO() docpath.save(stream) stream.seek(0) - return stream - return docpath + return Document(stream) + return Document(docpath) def __getattr__(self, name): return getattr(self.subdocx, name) diff --git a/tests/unit/test_objects.py b/tests/unit/test_objects.py index 5d71d96..1a9058b 100644 --- a/tests/unit/test_objects.py +++ b/tests/unit/test_objects.py @@ -1,4 +1,5 @@ import io +from pathlib import Path import struct import zlib @@ -187,6 +188,80 @@ def test_subdoc_from_document_object(make_docx): assert other.element.body.sectPr is not None +TEMPLATES = Path(__file__).resolve().parents[1] / "templates" + + +def _package_snapshot(doc): + """Every part of a document, with its content and relationships.""" + from docx.opc.part import XmlPart + from lxml import etree + + snap = {} + for part in doc.part.package.iter_parts(): + data = etree.tostring(part._element) if isinstance(part, XmlPart) else part.blob + rels = sorted((r.rId, r.reltype, r.target_ref) for r in part.rels.values()) + snap[str(part.partname)] = (data, rels) + return snap + + +def _doc_with_picture(): + doc = Document() + doc.add_paragraph("styled", style="Heading 1") + doc.add_paragraph("item", style="List Number") + doc.add_picture(io.BytesIO(PNG), width=Mm(10)) + return doc + + +@pytest.mark.parametrize( + "source", + ["picture", "merge_docx_subdoc.docx", "issue_621_subdoc.docx", "footnotes_tpl.docx", "pandoc_subdoc.docx"], +) +def test_subdoc_from_document_object_leaves_it_untouched(make_docx, source): + pytest.importorskip("docxcompose") + other = _doc_with_picture() if source == "picture" else Document(str(TEMPLATES / source)) + before = _package_snapshot(other) + + tpl = DocxTemplate(make_docx(["{{p a }}", "{{p b }}"])) + tpl.render({"a": tpl.new_subdoc(other), "b": tpl.new_subdoc(other)}) + doc = saved(tpl) + # styles, numbering, images, footnotes and every other part stay as they were + assert _package_snapshot(other) == before + if source == "picture": + assert body_text(doc).count("styled") == 2 + assert len(doc.inline_shapes) == 2 + for shape in doc.inline_shapes: + assert shape._inline.graphic.graphicData.pic.blipFill.blip.embed in doc.part.rels + + +def test_subdoc_from_document_with_custom_properties(make_docx): + pytest.importorskip("docxcompose") + from docxcompose.properties import CustomProperties + + other = Document() + other.add_paragraph("has props") + CustomProperties(other).add("Client", "ACME") + saved_other = io.BytesIO() + other.save(saved_other) + saved_other.seek(0) + other = Document(saved_other) + before = _package_snapshot(other) + + tpl = DocxTemplate(make_docx(["{{p sd }}"])) + tpl.render({"sd": tpl.new_subdoc(other)}) + assert body_text(saved(tpl)) == ["has props"] + assert _package_snapshot(other) == before + + +def test_subdoc_style_mapping_matches_python_docx(): + pytest.importorskip("docxcompose") + from docform.docx.subdoc import _style_ids_and_names + + doc = Document() + doc.styles.add_style("My Custom", 1) + expected = [(s.style_id, s.name) for s in doc.styles] + assert list(_style_ids_and_names(doc)) == expected + + def test_subdoc_from_rendered_template(make_docx): pytest.importorskip("docxcompose") sub_tpl = DocxTemplate(make_docx(["Hello {{ name }}"]))