diff options
author | Étienne Loks <etienne.loks@iggdrasil.net> | 2019-05-22 18:52:28 +0200 |
---|---|---|
committer | Étienne Loks <etienne.loks@iggdrasil.net> | 2019-05-22 18:52:28 +0200 |
commit | 1351334e7914608fc2de87b806846bc37f671097 (patch) | |
tree | 939f39f7bd4bfc50654d0c621777dd7b4bbae060 /ishtar_common/utils_secretary.py | |
parent | 702003ef31b47d3bfa31c515dc7fb304b3af7ffc (diff) | |
download | Ishtar-1351334e7914608fc2de87b806846bc37f671097.tar.bz2 Ishtar-1351334e7914608fc2de87b806846bc37f671097.zip |
Document template: manage height, with and aspect ratio for images
Diffstat (limited to 'ishtar_common/utils_secretary.py')
-rw-r--r-- | ishtar_common/utils_secretary.py | 56 |
1 files changed, 56 insertions, 0 deletions
diff --git a/ishtar_common/utils_secretary.py b/ishtar_common/utils_secretary.py new file mode 100644 index 000000000..6f605590e --- /dev/null +++ b/ishtar_common/utils_secretary.py @@ -0,0 +1,56 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +from secretary import Renderer +from PIL import Image +import re + + +RE_UNITS = re.compile("([.0-9]+)([a-z]+)") + + +def parse_value_unit(value): + m = RE_UNITS.match(value) + if not m: + return None, None + value, unit = m.groups() + value = float(value) + return value, unit + + +class IshtarSecretaryRenderer(Renderer): + def __init__(self, *args, **kwargs): + super(IshtarSecretaryRenderer, self).__init__(*args, **kwargs) + self.media_callback = self.ishtar_media_loader + # self.environment.filters['pad'] = pad_string + + def ishtar_media_loader(self, media, *args, **kwargs): + """Loads a file from the file system. + :param media: A file object or a relative or absolute path of a file. + :type media: unicode + """ + image_file, mime = self.fs_loader(media, *args, **kwargs) + if "width" in kwargs: + kwargs['frame_attrs']['svg:width'] = kwargs["width"] + if "height" in kwargs: + kwargs['frame_attrs']['svg:height'] = kwargs["height"] + if "keep_ratio" in args: + image = Image.open(image_file.name) + width, width_unit = parse_value_unit( + kwargs['frame_attrs']['svg:width']) + height, height_unit = parse_value_unit( + kwargs['frame_attrs']['svg:height']) + if "height" not in kwargs and width: + new_height = width * image.height / image.width + kwargs['frame_attrs']['svg:height'] = "{}{}".format( + new_height, width_unit + ) + if "width" not in kwargs and height: + new_width = height * image.width / image.height + kwargs['frame_attrs']['svg:width'] = "{}{}".format( + new_width, height_unit + ) + return image_file, mime + + + |