From 42e31c5060a61e42822a166928b7aa39da7867fc Mon Sep 17 00:00:00 2001 From: Étienne Loks Date: Wed, 22 May 2019 18:52:28 +0200 Subject: Document template: manage height, with and aspect ratio for images --- ishtar_common/utils_secretary.py | 56 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 ishtar_common/utils_secretary.py (limited to 'ishtar_common/utils_secretary.py') 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 + + + -- cgit v1.2.3