From e0d5eb0e0a82d62be5f01942084da8ad0f000596 Mon Sep 17 00:00:00 2001 From: Jean Marcos da Rosa Date: Tue, 9 Jul 2024 10:33:26 -0300 Subject: [PATCH] Added hyperlink option in InlineImage --- docxtpl/inline_image.py | 35 ++++++++++++++++++++++++++++++++--- 1 file changed, 32 insertions(+), 3 deletions(-) diff --git a/docxtpl/inline_image.py b/docxtpl/inline_image.py index 43af07b..e96eec6 100644 --- a/docxtpl/inline_image.py +++ b/docxtpl/inline_image.py @@ -4,7 +4,8 @@ @author: Eric Lapouyade """ - +from docx.oxml import OxmlElement, parse_xml +from docx.oxml.ns import qn class InlineImage(object): """Class to generate an inline image @@ -15,17 +16,45 @@ class InlineImage(object): image_descriptor = None width = None height = None + anchor = None - def __init__(self, tpl, image_descriptor, width=None, height=None): + def __init__(self, tpl, image_descriptor, width=None, height=None, anchor=None): self.tpl, self.image_descriptor = tpl, image_descriptor self.width, self.height = width, height + self.anchor = anchor + + def _add_hyperlink(self, run, url, part): + # Create a relationship for the hyperlink + r_id = part.relate_to(url, 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink', is_external=True) + + # Find the and element + docPr = run.xpath('.//wp:docPr')[0] + cNvPr = run.xpath('.//pic:cNvPr')[0] + + # Create the element + hlinkClick1 = OxmlElement('a:hlinkClick') + hlinkClick1.set(qn('r:id'), r_id) + hlinkClick2 = OxmlElement('a:hlinkClick') + hlinkClick2.set(qn('r:id'), r_id) + + # Insert the element right after the element + docPr.append(hlinkClick1) + cNvPr.append(hlinkClick2) + + return run def _insert_image(self): pic = self.tpl.current_rendering_part.new_pic_inline( self.image_descriptor, self.width, - self.height + self.height, ).xml + if self.anchor: + run = parse_xml(pic) + if run.xpath('.//a:blip'): + hyperlink = self._add_hyperlink(run, self.anchor, self.tpl.current_rendering_part) + pic = hyperlink.xml + return '%s' \ '' % pic