# -*- coding: utf-8 -*-
"""
Created : 2021-07-30
@author: Eric Lapouyade
"""
try:
from html import escape
except ImportError:
# cgi.escape is deprecated in python 3.7
from cgi import escape
class RichText(object):
"""class to generate Rich Text when using templates variables
This is much faster than using Subdoc class,
but this only for texts INSIDE an existing paragraph.
"""
def __init__(self, text=None, **text_prop):
self.xml = ""
if text:
self.add(text, **text_prop)
def add(
self,
text,
style=None,
color=None,
highlight=None,
size=None,
subscript=None,
superscript=None,
bold=False,
italic=False,
underline=False,
strike=False,
font=None,
url_id=None,
rtl=False,
lang=None,
):
# If a RichText is added
if isinstance(text, RichText):
self.xml += text.xml
return
# # If nothing to add : just return
# if text is None or text == "":
# return
# If not a string : cast to string (ex: int, dict etc...)
if not isinstance(text, (str, bytes)):
text = str(text)
if not isinstance(text, str):
text = text.decode("utf-8", errors="ignore")
text = escape(text)
prop = ""
if style:
prop += '' % style
if color:
if color[0] == "#":
color = color[1:]
prop += '' % color
if highlight:
if highlight[0] == "#":
highlight = highlight[1:]
prop += '' % highlight
if size:
prop += '' % size
prop += '' % size
if subscript:
prop += ''
if superscript:
prop += ''
if bold:
prop += ""
if rtl:
prop += ""
if italic:
prop += ""
if rtl:
prop += ""
if underline:
if underline not in [
"single",
"double",
"thick",
"dotted",
"dash",
"dotDash",
"dotDotDash",
"wave",
]:
underline = "single"
prop += '' % underline
if strike:
prop += ""
if font:
regional_font = ""
if ":" in font:
region, font = font.split(":", 1)
regional_font = ' w:{region}="{font}"'.format(font=font, region=region)
prop += ''.format(
font=font, regional_font=regional_font
)
if rtl:
prop += ''
if lang:
prop += '' % lang
xml = ""
if prop:
xml += "%s" % prop
xml += '%s' % text
if url_id:
xml = '%s' % (
url_id,
xml,
)
self.xml += xml
def __unicode__(self):
return self.xml
def __str__(self):
return self.xml
def __html__(self):
return self.xml
class RichTextParagraph(object):
"""class to generate Rich Text Paragraphs when using templates variables
This is much faster than using Subdoc class,
but this only for texts OUTSIDE an existing paragraph.
"""
def __init__(self, text=None, **text_prop):
self.xml = ""
if text:
self.add(text, **text_prop)
def add(
self,
text,
parastyle=None,
):
# If a RichText is added
if not isinstance(text, RichText):
text = RichText(text)
prop = ""
if parastyle:
prop += '' % parastyle
xml = ""
if prop:
xml += "%s" % prop
xml += text.xml
xml += ""
self.xml += xml
def __unicode__(self):
return self.xml
def __str__(self):
return self.xml
def __html__(self):
return self.xml
R = RichText
RP = RichTextParagraph