diff --git a/docx/document.py b/docx/document.py index 6493c458b..6566aaebd 100644 --- a/docx/document.py +++ b/docx/document.py @@ -3,6 +3,7 @@ """|Document| and closely related objects""" from __future__ import absolute_import, division, print_function, unicode_literals +from docx.oxml.textbox import find_textboxes from docx.blkcntnr import BlockItemContainer from docx.enum.section import WD_SECTION @@ -185,6 +186,13 @@ def _body(self): self.__body = _Body(self._element.body, self) return self.__body + @property + def textboxes(self): + """ + List all text box objects in the document. + """ + return find_textboxes(self._element) + class _Body(BlockItemContainer): """ diff --git a/docx/oxml/__init__.py b/docx/oxml/__init__.py index 093c1b45b..1674594d0 100644 --- a/docx/oxml/__init__.py +++ b/docx/oxml/__init__.py @@ -246,3 +246,23 @@ def OxmlElement(nsptag_str, attrs=None, nsdecls=None): register_element_cls('w:br', CT_Br) register_element_cls('w:r', CT_R) register_element_cls('w:t', CT_Text) + + +from .textbox import ( # noqa + AlternateContent, + AlternateContentChoice, + AlternateContentFallback, + Anchor, + CT_LinkedTextboxInformation, + CT_TextBoxContent, + CT_TextboxInfo, + CT_WordprocessingShape, +) +register_element_cls("mc:AlternateContent", AlternateContent) +register_element_cls("mc:Choice", AlternateContentChoice) +register_element_cls("mc:Fallback", AlternateContentFallback) +register_element_cls("wp:anchor", Anchor) +register_element_cls("wps:linkedTxbx", CT_LinkedTextboxInformation) +register_element_cls("w:txbxContent", CT_TextBoxContent) +register_element_cls("wps:txbx", CT_TextboxInfo) +register_element_cls("wps:wsp", CT_WordprocessingShape) \ No newline at end of file diff --git a/docx/oxml/ns.py b/docx/oxml/ns.py index 6b0861284..f31847bce 100644 --- a/docx/oxml/ns.py +++ b/docx/oxml/ns.py @@ -16,12 +16,15 @@ "dcterms": "http://purl.org/dc/terms/", "dgm": "http://schemas.openxmlformats.org/drawingml/2006/diagram", "m": "http://schemas.openxmlformats.org/officeDocument/2006/math", + "mc": "http://schemas.openxmlformats.org/markup-compatibility/2006", "pic": "http://schemas.openxmlformats.org/drawingml/2006/picture", "r": "http://schemas.openxmlformats.org/officeDocument/2006/relationships", "sl": "http://schemas.openxmlformats.org/schemaLibrary/2006/main", + "v": "urn:schemas-microsoft-com:vml", "w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main", - 'w14': "http://schemas.microsoft.com/office/word/2010/wordml", + "w14": "http://schemas.microsoft.com/office/word/2010/wordml", "wp": "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing", + "wps": "http://schemas.microsoft.com/office/word/2010/wordprocessingShape", "xml": "http://www.w3.org/XML/1998/namespace", "xsi": "http://www.w3.org/2001/XMLSchema-instance", } diff --git a/docx/oxml/textbox.py b/docx/oxml/textbox.py new file mode 100644 index 000000000..a4faea7fc --- /dev/null +++ b/docx/oxml/textbox.py @@ -0,0 +1,167 @@ +# encoding: utf-8 + +"""Custom element classes for textboxed""" + +from docx.oxml.text import paragraph +from ..blkcntnr import BlockItemContainer +from ..shared import ElementProxy +from .simpletypes import XsdUnsignedInt, XsdString +from .xmlchemy import ( + BaseOxmlElement, + OneAndOnlyOne, + OneOrMore, + RequiredAttribute, + ZeroOrMore, + ZeroOrOne, +) + +XPATH_CHOICE = "./mc:Choice/w:drawing/wp:anchor/a:graphic/a:graphicData/wps:wsp/wps:txbx\ + /w:txbxContent" +XPATH_FALLBACK = "./mc:Fallback/w:pict/v:*/v:textbox/w:txbxContent" + + +class CT_TextBoxContent(BaseOxmlElement): + """ + ```` element + """ + + p = ZeroOrMore("w:p") + + +class CT_LinkedTextboxInformation(BaseOxmlElement): + """ + ```` element + """ + + identifier = RequiredAttribute("id", XsdUnsignedInt) + seq = RequiredAttribute("seq", XsdUnsignedInt) + + +class CT_TextboxInfo(BaseOxmlElement): + """ + ```` element + """ + + txbxContent = OneAndOnlyOne("w:txbxContent") + + +class CT_WordprocessingShape(BaseOxmlElement): + """ + ```` element + """ + + txbx = ZeroOrOne("wps:txbx") + + +class Anchor(BaseOxmlElement): + """ + ```` element + """ + + # I think there has to be exactly one, not sure + graphic = ZeroOrMore("a:graphic") + + +class TextBox(ElementProxy): + """Text box class that stores two TextBoxContent objects + + The reason why it needs to store two textboxes is because two copies with different + formatting are stored in the document for legacy reasons. + """ + + def __init__(self, element): + """ + Initialize using an ```` object + """ + super(TextBox, self).__init__(element) + + try: + (tbox1,) = element.xpath(XPATH_CHOICE) + (tbox2,) = element.xpath(XPATH_FALLBACK) + except ValueError as err: + raise ValueError( + "This element is not a text box; it should contain precisely two \ + ```` objects" + ) + self.tbox1 = TextBoxContent(tbox1, self) + self.tbox2 = TextBoxContent(tbox2, self) + + def add_paragraph(self, text="", style=None): + paragraph = self.tbox1.add_paragraph(text=text, style=style) + _ = self.tbox2.add_paragraph(text=text, style=style) + return paragraph + + def add_table(self, rows, cols, width): + tbl = self.tbox1.add_table(rows, cols, width) + _ = self.tbox2.add_table(rows, cols, width) + return tbl + + @property + def paragraphs(self): + return self.tbox1.paragraphs + + @property + def tables(self): + return self.tbox1.tables + + @property + def text(self): + return "\n".join(p.text for p in self.paragraphs) + + @text.setter + def text(self, text): + for tbox in [self.tbox1, self.tbox2]: + tbox.clear_content() + p = tbox._add_paragraph() + r = p.add_run() + r.text = text + + def clear_content(self): + self.tbox1.clear_content() + self.tbox2.clear_content() + + +class TextBoxContent(BlockItemContainer): + def clear_content(self): + for c in self._element[:]: + self._element.remove(c) + + +class AlternateContentChoice(BaseOxmlElement): + """ + ```` element + """ + + requires = RequiredAttribute("Requires", XsdString) + + +class AlternateContentFallback(BaseOxmlElement): + """ + ```` element + """ + + +class AlternateContent(BaseOxmlElement): + """ + ```` element + """ + + choice = OneOrMore("mc:AlternateChoice") + fallback = OneOrMore("mc:Fallback") + + +def find_textboxes(element): + """ + List all text box objects in the document. + + Looks for all ```` elements, and selects those + which contain a text box. + """ + alt_cont_elems = element.xpath(".//mc:AlternateContent") + text_boxes = [] + for elem in alt_cont_elems: + tbox1 = elem.xpath(XPATH_CHOICE) + tbox2 = elem.xpath(XPATH_FALLBACK) + if len(tbox1) == 1 and len(tbox2) == 1: + text_boxes.append(TextBox(elem)) + return text_boxes