diff options
| author | Michael Williamson <mike@zwobble.org> | 2014-07-08 11:03:27 +0100 |
|---|---|---|
| committer | Michael Williamson <mike@zwobble.org> | 2014-07-08 11:03:27 +0100 |
| commit | 5a484ab1f55d36977e8ed15aefef3daff36d1fb2 (patch) | |
| tree | 0d2f810af7b42303dda1764efa89882100bb0a7c /mammoth | |
| parent | 0e046e91f26c8c222dc9b6a683514fe5a5895675 (diff) | |
Extract common image conversion code
Diffstat (limited to 'mammoth')
| -rw-r--r-- | mammoth/__init__.py | 4 | ||||
| -rw-r--r-- | mammoth/conversion.py | 12 | ||||
| -rw-r--r-- | mammoth/images.py | 9 |
3 files changed, 16 insertions, 9 deletions
diff --git a/mammoth/__init__.py b/mammoth/__init__.py index 05e2167..0b524b1 100644 --- a/mammoth/__init__.py +++ b/mammoth/__init__.py @@ -1,5 +1,7 @@ from .results import Result -from . import docx, conversion, options, documents +from . import docx, conversion, options, documents, images + +__all__ = ["convert_to_html", "extract_raw_text", "images"] def convert_to_html(fileobj, transform_document=None, **kwargs): diff --git a/mammoth/conversion.py b/mammoth/conversion.py index 0349774..715e5e0 100644 --- a/mammoth/conversion.py +++ b/mammoth/conversion.py @@ -1,7 +1,7 @@ import base64 import io -from . import documents, results, html_paths +from . import documents, results, html_paths, images from .html_generation import HtmlGenerator, satisfy_html_path @@ -29,7 +29,7 @@ class DocumentConverter(object): documents.Table: self._convert_table, documents.TableRow: self._convert_table_row, documents.TableCell: self._convert_table_cell, - documents.Image: convert_image or self._convert_image, + documents.Image: convert_image or images.inline(self._convert_image), } @@ -99,17 +99,13 @@ class DocumentConverter(object): html_generator.end() - def _convert_image(self, image, html_generator): + def _convert_image(self, image): with image.open() as image_bytes: encoded_src = base64.b64encode(image_bytes.read()).decode("ascii") - attributes = { + return { "src": "data:{0};base64,{1}".format(image.content_type, encoded_src) } - if image.alt_text: - attributes["alt"] = image.alt_text - - html_generator.self_closing("img", attributes) def _convert_elements_to_html(self, elements, html_generator): diff --git a/mammoth/images.py b/mammoth/images.py new file mode 100644 index 0000000..713f739 --- /dev/null +++ b/mammoth/images.py @@ -0,0 +1,9 @@ +def inline(func): + def convert_image(image, html_generator): + attributes = func(image).copy() + if image.alt_text: + attributes["alt"] = image.alt_text + + html_generator.self_closing("img", attributes) + + return convert_image |
