96
|
1 |
import string
|
|
2 |
import types
|
|
3 |
import sys
|
|
4 |
import os
|
|
5 |
import copy
|
|
6 |
|
|
7 |
try:
|
|
8 |
from xml.parsers import xmllib
|
|
9 |
_xmllib_newStyle = 1
|
|
10 |
except ImportError:
|
|
11 |
import xmllib
|
|
12 |
_xmllib_newStyle = 0
|
|
13 |
|
|
14 |
from reportlab.lib.colors import stringToColor, white, black, red, Color
|
|
15 |
from reportlab.lib.fonts import tt2ps, ps2tt
|
|
16 |
|
|
17 |
sizeDelta = 2 # amount to reduce font size by for super and sub script
|
|
18 |
subFraction = 0.5 # fraction of font size that a sub script should be lowered
|
|
19 |
superFraction = 0.5 # fraction of font size that a super script should be raised
|
|
20 |
|
102
|
21 |
def _num(s):
|
|
22 |
try:
|
|
23 |
return int(s)
|
|
24 |
except ValueError:
|
|
25 |
return float(s)
|
|
26 |
|
96
|
27 |
#characters not supported: epsi, Gammad, gammad, kappav, rhov, Upsi, upsi
|
|
28 |
greeks = {
|
|
29 |
'alpha':'a',
|
|
30 |
'beta':'b',
|
|
31 |
'chi':'c',
|
|
32 |
'Delta':'D',
|
|
33 |
'delta':'d',
|
|
34 |
'epsiv':'e',
|
|
35 |
'eta':'h',
|
|
36 |
'Gamma':'G',
|
|
37 |
'gamma':'g',
|
|
38 |
'iota':'i',
|
|
39 |
'kappa':'k',
|
|
40 |
'Lambda':'L',
|
|
41 |
'lambda':'l',
|
|
42 |
'mu':'m',
|
|
43 |
'nu':'n',
|
|
44 |
'Omega':'W',
|
|
45 |
'omega':'w',
|
|
46 |
'omicron':'x',
|
|
47 |
'Phi':'F',
|
|
48 |
'phi':'f',
|
|
49 |
'phiv':'j',
|
|
50 |
'Pi':'P',
|
|
51 |
'pi':'p',
|
|
52 |
'piv':'v',
|
|
53 |
'Psi':'Y',
|
|
54 |
'psi':'y',
|
|
55 |
'rho':'r',
|
|
56 |
'Sigma':'S',
|
|
57 |
'sigma':'s',
|
|
58 |
'sigmav':'V',
|
|
59 |
'tau':'t',
|
|
60 |
'Theta':'Q',
|
|
61 |
'theta':'q',
|
|
62 |
'thetav':'j',
|
|
63 |
'Xi':'X',
|
|
64 |
'xi':'x',
|
|
65 |
'zeta':'z'
|
|
66 |
}
|
|
67 |
|
|
68 |
#------------------------------------------------------------------------
|
|
69 |
class ParaFrag:
|
|
70 |
"""class ParaFrag contains the intermediate representation of string
|
|
71 |
segments as they are being parsed by the XMLParser.
|
|
72 |
"""
|
102
|
73 |
def __init__(self,**attr):
|
|
74 |
for k,v in attr.items():
|
|
75 |
setattr(self,k,v)
|
|
76 |
|
|
77 |
def clone(self,**attr):
|
|
78 |
n = apply(ParaFrag,(),self.__dict__)
|
|
79 |
if attr != {}: apply(ParaFrag.__init__,(n,),attr)
|
|
80 |
return n
|
96
|
81 |
|
|
82 |
#------------------------------------------------------------------
|
|
83 |
# The ParaFormatter will be able to format the following xml
|
|
84 |
# tags:
|
|
85 |
# < b > < /b > - bold
|
|
86 |
# < i > < /i > - italics
|
|
87 |
# < u > < /u > - underline
|
|
88 |
# < super > < /super > - superscript
|
|
89 |
# < sub > < /sub > - subscript
|
|
90 |
# <font name=fontfamily/fontname color=colorname size=float>
|
|
91 |
#
|
|
92 |
# It will also be able to handle any MathML specified Greek characters.
|
|
93 |
#------------------------------------------------------------------
|
|
94 |
class ParaParser(xmllib.XMLParser):
|
|
95 |
|
|
96 |
#----------------------------------------------------------
|
|
97 |
# First we will define all of the xml tag handler functions.
|
|
98 |
#
|
|
99 |
# start_<tag>(attributes)
|
|
100 |
# end_<tag>()
|
|
101 |
#
|
|
102 |
# While parsing the xml ParaFormatter will call these
|
|
103 |
# functions to handle the string formatting tags.
|
|
104 |
# At the start of each tag the corresponding field will
|
|
105 |
# be set to 1 and at the end tag the corresponding field will
|
|
106 |
# be set to 0. Then when handle_data is called the options
|
|
107 |
# for that data will be aparent by the current settings.
|
|
108 |
#----------------------------------------------------------
|
|
109 |
|
|
110 |
#### bold
|
|
111 |
def start_b( self, attributes ):
|
|
112 |
self._push(bold=1)
|
|
113 |
|
|
114 |
def end_b( self ):
|
|
115 |
self._pop(bold=1)
|
|
116 |
|
|
117 |
#### italics
|
|
118 |
def start_i( self, attributes ):
|
|
119 |
self._push(italic=1)
|
|
120 |
|
|
121 |
def end_i( self ):
|
|
122 |
self._pop(italic=1)
|
|
123 |
|
|
124 |
#### underline
|
|
125 |
def start_u( self, attributes ):
|
|
126 |
self._push(underline=1)
|
|
127 |
|
|
128 |
def end_u( self ):
|
|
129 |
self._pop(underline=1)
|
|
130 |
|
|
131 |
#### super script
|
|
132 |
def start_super( self, attributes ):
|
|
133 |
self._push(super=1)
|
|
134 |
|
|
135 |
def end_super( self ):
|
|
136 |
self._pop(super=1)
|
|
137 |
|
|
138 |
#### sub script
|
|
139 |
def start_sub( self, attributes ):
|
|
140 |
self._push(sub=1)
|
|
141 |
|
|
142 |
def end_sub( self ):
|
|
143 |
self._pop(sub=1)
|
|
144 |
|
|
145 |
#### greek script
|
|
146 |
if _xmllib_newStyle:
|
|
147 |
def handle_entityref(self,name):
|
|
148 |
if greeks.has_key(name):
|
|
149 |
self._push(greek=1)
|
|
150 |
self.handle_data(greeks[name])
|
|
151 |
self._pop(greek=1)
|
|
152 |
else:
|
|
153 |
xmllib.XMLParser.handle_entityref(self,name)
|
|
154 |
else:
|
|
155 |
def start_greekLetter(self, attributes,letter):
|
|
156 |
self._push(greek=1)
|
|
157 |
self.handle_data(letter)
|
|
158 |
|
|
159 |
def start_greek(self, attributes):
|
|
160 |
self._push(greek=1)
|
|
161 |
|
|
162 |
def end_greek(self):
|
|
163 |
self._pop(greek=1)
|
|
164 |
|
|
165 |
#things which are valid font attributes
|
102
|
166 |
_fontAttrMap = {'size': ('fontSize',_num),
|
|
167 |
'name': ('fontName', None),
|
|
168 |
'color':('textColor',stringToColor)}
|
96
|
169 |
def start_font(self,attr):
|
|
170 |
A = {}
|
|
171 |
for i, j in self._fontAttrMap.items():
|
|
172 |
if attr.has_key(i):
|
|
173 |
func = j[1]
|
|
174 |
val = attr[i]
|
102
|
175 |
try:
|
|
176 |
A[j[0]] = (func is None) and val or apply(func,(val,))
|
|
177 |
except:
|
|
178 |
self.syntax_error('%s: invalid value %s'%(i,val))
|
113
|
179 |
apply(self._push,(),A)
|
96
|
180 |
|
|
181 |
def end_font(self):
|
|
182 |
self._pop()
|
|
183 |
|
|
184 |
def _push(self,**kw):
|
|
185 |
frag = copy.copy(self._stack[-1])
|
|
186 |
for k, v in kw.items():
|
|
187 |
setattr(frag,k,v)
|
|
188 |
self._stack.append(frag)
|
|
189 |
|
|
190 |
def _pop(self,**kw):
|
|
191 |
frag = self._stack[-1]
|
|
192 |
del self._stack[-1]
|
|
193 |
for k, v in kw.items():
|
|
194 |
assert getattr(frag,k)==v
|
|
195 |
return frag
|
|
196 |
|
|
197 |
#----------------------------------------------------------------
|
|
198 |
|
|
199 |
def __init__(self,verbose=0):
|
|
200 |
if _xmllib_newStyle:
|
|
201 |
xmllib.XMLParser.__init__(self,verbose=verbose)
|
|
202 |
else:
|
|
203 |
xmllib.XMLParser.__init__(self)
|
|
204 |
# set up handlers for various tags
|
|
205 |
self.elements = { 'b': (self.start_b, self.end_b),
|
|
206 |
'u': (self.start_u, self.end_u),
|
|
207 |
'i': (self.start_i, self.end_i),
|
|
208 |
'super': (self.start_super, self.end_super),
|
|
209 |
'sub': (self.start_sub, self.end_sub),
|
|
210 |
'font': (self.start_font, self.end_font),
|
|
211 |
'greek': (self.start_greek, self.end_greek)
|
|
212 |
}
|
|
213 |
|
|
214 |
# automatically add handlers for all of the greek characters
|
|
215 |
for item in greeks.keys():
|
|
216 |
self.elements[item] = (lambda attr,self=self,letter=greeks[item]:
|
|
217 |
self.start_greekLetter(attr,letter), self.end_greek)
|
|
218 |
|
|
219 |
# set up dictionary for greek characters, this is a class variable
|
|
220 |
self.entitydefs = copy.copy(self.entitydefs)
|
|
221 |
for item in greeks.keys():
|
|
222 |
self.entitydefs[item] = '<%s/>' % item
|
|
223 |
|
|
224 |
def _reset(self, style):
|
|
225 |
'''reset the parser'''
|
|
226 |
xmllib.XMLParser.reset(self)
|
|
227 |
|
|
228 |
# initialize list of string segments to empty
|
|
229 |
self.errors = []
|
|
230 |
self.fragList = []
|
|
231 |
|
|
232 |
# initialize frag values
|
|
233 |
frag = ParaFrag()
|
|
234 |
frag.sub = 0
|
|
235 |
frag.super = 0
|
112
|
236 |
frag.rise = 0
|
102
|
237 |
frag.fontName, frag.bold, frag.italic = ps2tt(style.fontName)
|
96
|
238 |
frag.fontSize = style.fontSize
|
|
239 |
frag.underline = 0
|
|
240 |
frag.greek = 0
|
102
|
241 |
frag.textColor = style.textColor
|
96
|
242 |
self._stack = [frag]
|
|
243 |
|
|
244 |
def syntax_error(self,message):
|
|
245 |
if message[:11]=="attribute `" and message[-18:]=="' value not quoted": return
|
|
246 |
self.errors.append(message)
|
|
247 |
|
|
248 |
#----------------------------------------------------------------
|
|
249 |
def handle_data(self,data):
|
|
250 |
"Creates an intermediate representation of string segments."
|
|
251 |
|
|
252 |
frag = copy.copy(self._stack[-1])
|
102
|
253 |
#save our data
|
|
254 |
frag.text = data
|
96
|
255 |
|
|
256 |
# if sub and super are both one they will cancel each other out
|
|
257 |
if frag.sub == 1 and frag.super == 1:
|
|
258 |
frag.sub = 0
|
|
259 |
frag.super = 0
|
|
260 |
|
112
|
261 |
if frag.sub:
|
|
262 |
frag.rise = -frag.fontSize*subFraction
|
|
263 |
frag.fontSize = max(frag.fontSize-sizeDelta,3)
|
115
|
264 |
elif frag.super:
|
112
|
265 |
frag.rise = frag.fontSize*superFraction
|
115
|
266 |
frag.fontSize = max(frag.fontSize-sizeDelta,3)
|
112
|
267 |
|
102
|
268 |
if frag.greek: frag.fontName = 'symbol'
|
96
|
269 |
# bold, italic, and underline
|
102
|
270 |
frag.fontName = tt2ps(frag.fontName,frag.bold,frag.italic)
|
96
|
271 |
|
|
272 |
self.fragList.append(frag)
|
|
273 |
|
|
274 |
#----------------------------------------------------------------
|
102
|
275 |
def parse(self, text, style):
|
96
|
276 |
"""Given a formatted string will return a list of
|
|
277 |
ParaFrag objects with their calculated widths.
|
|
278 |
If errors occur None will be returned and the
|
|
279 |
self.errors holds a list of the error messages.
|
|
280 |
"""
|
|
281 |
|
|
282 |
# the xmlparser requires that all text be surrounded by xml
|
|
283 |
# tags, therefore we must throw some unused flags around the
|
|
284 |
# given string
|
|
285 |
self._reset(style) # reinitialise the parser
|
102
|
286 |
self.feed("<ReportLabParagraph>"+text+"</ReportLabParagraph>")
|
96
|
287 |
self.close() # force parsing to complete
|
|
288 |
if len(self.errors)==0:
|
|
289 |
fragList = self.fragList
|
|
290 |
self.fragList = []
|
|
291 |
return fragList
|
|
292 |
else:
|
|
293 |
return None
|
|
294 |
|
|
295 |
if __name__=='__main__':
|
|
296 |
from reportlab.platypus.layout import cleanBlockQuotedText
|
|
297 |
_parser=ParaParser()
|
|
298 |
|
|
299 |
style=ParaFrag()
|
|
300 |
style.fontName='Times-Roman'
|
|
301 |
style.fontSize = 12
|
|
302 |
style.textColor = black
|
|
303 |
|
|
304 |
text='''
|
|
305 |
<b><i><greek>a</greek>D</i></b>β
|
|
306 |
<font name="helvetica" size="15" color=green>
|
|
307 |
Tell me, O muse, of that ingenious hero who travelled far and wide
|
113
|
308 |
after</font> he had sacked the famous town of Troy. Many cities did he visit,
|
96
|
309 |
and many were the nations with whose manners and customs he was acquainted;
|
|
310 |
moreover he suffered much by sea while trying to save his own life
|
|
311 |
and bring his men safely home; but do what he might he could not save
|
|
312 |
his men, for they perished through their own sheer folly in eating
|
|
313 |
the cattle of the Sun-god Hyperion; so the god prevented them from
|
|
314 |
ever reaching home. Tell me, too, about all these things, O daughter
|
115
|
315 |
of Jove, from whatsoever source you<super>1</super> may know them.
|
96
|
316 |
'''
|
|
317 |
text = cleanBlockQuotedText(text)
|
|
318 |
rv = _parser.parse(text,style)
|
|
319 |
if rv is None:
|
|
320 |
for l in _parser.errors:
|
|
321 |
print l
|
|
322 |
else:
|
|
323 |
for l in rv:
|
115
|
324 |
print l.fontName,l.fontSize,l.textColor,l.bold, l.rise, l.text[:25]
|