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