From 2fcc877a3513b79b9217a7575136e7711a2a3875 Mon Sep 17 00:00:00 2001 From: Michael Williamson Date: Thu, 4 Feb 2016 08:38:13 +0000 Subject: Handle missing paragraph styles in the source document --- mammoth/docx/body_xml.py | 29 ++++++++++++++++++++++------- 1 file changed, 22 insertions(+), 7 deletions(-) (limited to 'mammoth') diff --git a/mammoth/docx/body_xml.py b/mammoth/docx/body_xml.py index f66eeae..854ccf2 100644 --- a/mammoth/docx/body_xml.py +++ b/mammoth/docx/body_xml.py @@ -100,6 +100,7 @@ def _create_reader(numbering, content_types, relationships, styles, docx_file, f def paragraph(element): + messages = [] properties = element.find_child_or_null("w:pPr") style_id = properties \ .find_child_or_null("w:pStyle") \ @@ -108,19 +109,29 @@ def _create_reader(numbering, content_types, relationships, styles, docx_file, f if style_id is None: style_name = None else: - style_name = styles.find_paragraph_style_by_id(style_id).name + style = styles.find_paragraph_style_by_id(style_id) + if style is None: + style_name = None + messages.append(_undefined_style_warning("Paragraph", style_id)) + else: + style_name = style.name numbering = _read_numbering_properties(properties.find_child_or_null("w:numPr")) return _read_xml_elements(element.children) \ - .map(lambda children: documents.paragraph( - children=children, - style_id=style_id, - style_name=style_name, - numbering=numbering, - )) \ + .bind(lambda children: _element_result_with_messages( + documents.paragraph( + children=children, + style_id=style_id, + style_name=style_name, + numbering=numbering, + ), + messages)) \ .append_extra() + def _undefined_style_warning(style_type, style_id): + return results.warning("{0} style with ID {1} was referenced but not defined in the document".format(style_type, style_id)) + def _read_numbering_properties(element): num_id = element.find_child_or_null("w:numId").attributes.get("w:val") level_index = element.find_child_or_null("w:ilvl").attributes.get("w:val") @@ -341,6 +352,10 @@ class _ReadResult(object): result = self._result.map(lambda value: func(value[0])) return _ReadResult(result.value, self.extra, result.messages) + def bind(self, func): + result = self._result.bind(lambda value: func(value[0])) + return _ReadResult(result.value, self.extra, result.messages) + def to_extra(self): return _ReadResult(None, _concat(self.extra, self.value), self.messages) -- cgit v1.2.3