From 72b6754a18e25082705c3c79e2a7e969d5fe0774 Mon Sep 17 00:00:00 2001 From: ChabErch Date: Sun, 4 Oct 2020 23:09:41 +0300 Subject: [PATCH] Add line break resolving with styles preserving --- docxtpl/__init__.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/docxtpl/__init__.py b/docxtpl/__init__.py index aa1b1ee..a697340 100644 --- a/docxtpl/__init__.py +++ b/docxtpl/__init__.py @@ -27,6 +27,7 @@ import six import binascii import os import zipfile +from functools import partial NEWLINE_XML = '' NEWPARAGRAPH_XML = '' @@ -234,8 +235,31 @@ class DocxTemplate(object): .replace('}_}', '}}') .replace('{_%', '{%') .replace('%_}', '%}')) + dst_xml = self.resolve_listing(dst_xml) return dst_xml + def resolve_listing(self, xml): + xml = xml.replace('\n', NEWLINE_XML) + xml = xml.replace('\t', TAB_XML) + xml = xml.replace('\f', PAGE_BREAK) + + def resolve_run(paragraph_properties, m): + run_properties = re.search(r'.*', m[0]) + run_properties = run_properties[0] if run_properties else '' + return m[0].replace('\a', f'{paragraph_properties}{run_properties}') + + def resolve_paragraph(m): + paragraph_properties = re.search(r'.*', m[0]) + paragraph_properties = paragraph_properties[0] if paragraph_properties else '' + + p_resolve_run = partial(resolve_run, paragraph_properties) + + return re.sub(r']*)?>.*?', p_resolve_run, m[0]) + + xml = re.sub(r']*)?>.*?', resolve_paragraph, xml) + + return xml + def build_xml(self, context, jinja_env=None): xml = self.get_xml() xml = self.patch_xml(xml)