File: richtext.py

package info (click to toggle)
python-docx-template 0.20.0%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 2,404 kB
  • sloc: python: 1,742; makefile: 163
file content (180 lines) | stat: -rw-r--r-- 4,650 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
# -*- 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 += '<w:rStyle w:val="%s"/>' % style
        if color:
            if color[0] == "#":
                color = color[1:]
            prop += '<w:color w:val="%s"/>' % color
        if highlight:
            if highlight[0] == "#":
                highlight = highlight[1:]
            prop += '<w:shd w:fill="%s"/>' % highlight
        if size:
            prop += '<w:sz w:val="%s"/>' % size
            prop += '<w:szCs w:val="%s"/>' % size
        if subscript:
            prop += '<w:vertAlign w:val="subscript"/>'
        if superscript:
            prop += '<w:vertAlign w:val="superscript"/>'
        if bold:
            prop += "<w:b/>"
            if rtl:
                prop += "<w:bCs/>"
        if italic:
            prop += "<w:i/>"
            if rtl:
                prop += "<w:iCs/>"
        if underline:
            if underline not in [
                "single",
                "double",
                "thick",
                "dotted",
                "dash",
                "dotDash",
                "dotDotDash",
                "wave",
            ]:
                underline = "single"
            prop += '<w:u w:val="%s"/>' % underline
        if strike:
            prop += "<w:strike/>"
        if font:
            regional_font = ""
            if ":" in font:
                region, font = font.split(":", 1)
                regional_font = ' w:{region}="{font}"'.format(font=font, region=region)
            prop += '<w:rFonts w:ascii="{font}" w:hAnsi="{font}" w:cs="{font}"{regional_font}/>'.format(
                font=font, regional_font=regional_font
            )
        if rtl:
            prop += '<w:rtl w:val="true"/>'
        if lang:
            prop += '<w:lang w:val="%s"/>' % lang
        xml = "<w:r>"
        if prop:
            xml += "<w:rPr>%s</w:rPr>" % prop
        xml += '<w:t xml:space="preserve">%s</w:t></w:r>' % text
        if url_id:
            xml = '<w:hyperlink r:id="%s" w:tgtFrame="_blank">%s</w:hyperlink>' % (
                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 += '<w:pStyle w:val="%s"/>' % parastyle

        xml = "<w:p>"
        if prop:
            xml += "<w:pPr>%s</w:pPr>" % prop
        xml += text.xml
        xml += "</w:p>"
        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