forked from aquavitae/svg2rlg
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsvg2rlg.py
1512 lines (1209 loc) · 47.6 KB
/
svg2rlg.py
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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
svg2rlg is a tool to convert from SVG to reportlab graphics.
License: BSD
version 0.4.0
"""
import os
import re
from gzip import GzipFile
from xml.etree import ElementTree as etree
from reportlab.graphics import renderPDF
from reportlab.graphics.shapes import Drawing, Group, String, Line, Rect, Image
from reportlab.graphics.shapes import Circle, Ellipse, Polygon, PolyLine, Path
from reportlab.graphics.shapes import mmult
from reportlab.lib.units import toLength
import reportlab.lib.colors as colors
class SVGError(Exception):
pass
EOF = object()
class Lexer:
"""
This style of implementation was inspired by this article:
http://www.gooli.org/blog/a-simple-lexer-in-python/
"""
Float = r'[-\+]?(?:(?:\d*\.\d+)|(?:\d+\.)|(?:\d+))(?:[Ee][-\+]?\d+)?'
Int = r'[-\+]?\d+'
lexicon = None
ignore = None
callbacks = None
def __init__(self):
lexicon = self.lexicon
# create internal names for group matches
groupnames = dict(('lexer_%d' % idx, item[0])
for idx, item in enumerate(lexicon))
self.groupnames = groupnames
# assemble regex parts to one regex
igroupnames = dict((value, name) for name, value in groupnames.items())
regex_parts = ('(?P<%s>%s)' % (igroupnames[cls], regs)
for cls, regs in lexicon)
self.regex_string = '|'.join(regex_parts)
self.regex = re.compile(self.regex_string)
def lex(self, text):
"""
Yield (token_type, data) tokens.
The last token will be (EOF, None) where EOF
"""
regex = self.regex
groupnames = self.groupnames
ignore = self.ignore or set()
callbacks = self.callbacks or dict()
position = 0
size = len(text)
while position < size:
match = regex.match(text, position)
if match is None:
raise SVGError('Unknown token at position %d' % position)
position = match.end()
cls = groupnames[match.lastgroup]
value = match.group(match.lastgroup)
if cls in ignore:
continue
if cls in callbacks:
value = callbacks[cls](self, value)
yield (cls, value)
yield (EOF, None)
# Parse SVG length units
length_pattern = r"""
^ # match start of line
\s* # ignore whitespace
(?P<value>[-\+]?\d*\.?\d*([eE][-\+]?\d+)?) # match float or int value
(?P<unit>.+)? # match any chars
\s* # ignore whitespace
$ # match end of line
"""
length_match = re.compile(length_pattern, re.X).match
def parseLength(length):
"""
Convert length to reportlab points.
"""
match = length_match(length)
if match is None:
raise SVGError("Not a valid length unit: '%s'" % length)
value = match.group('value')
unit = match.group('unit') or ''
if not value:
raise SVGError("Not a valid length unit: '%s'" % length)
if not unit:
if value[0] == 'e' or value[0] == 'E':
return float('1' + value)
else:
return float(value)
elif unit in ('em', 'ex', 'px', '%'):
# ignoring relative units
return float(value)
elif unit == 'pc':
return toLength(value + 'pica')
elif unit in ('mm', 'cm', 'in', 'i', 'pt', 'pica'):
return toLength(length)
else:
raise SVGError("Unknown unit '%s'" % unit)
# Parse SVG color definitions
color_pattern = r"""
^(
(?P<named>
\w+
) |
(?P<hex>
[#]
(?P<hex_r>[a-zA-Z0-9]{2})
(?P<hex_rg>[a-zA-Z0-9]{2})
(?P<hex_rb>[a-zA-Z0-9]{2})
) |
(?P<hexshort>
[#]
(?P<hexshort_r>[a-zA-Z0-9])
(?P<hexshort_g>[a-zA-Z0-9])
(?P<hexshort_b>[a-zA-Z0-9])
) |
(?P<rgbint>
[rR][gG][bB]
\(
(?P<rgbint_r>\d{1,3})
,\s?
(?P<rgbint_g>\d{1,3})
,\s?
(?P<rgbint_b>\d{1,3})
\)
) |
(?P<rgb>
[rR][gG][bB]
\(
(?P<rgb_r>\d+\.?\d*)
\%
,\s?
(?P<rgb_g>\d+\.?\d*)
\%
,\s?
(?P<rgb_b>\d+\.?\d*)
\%
\)
)
)$
"""
color_match = re.compile(color_pattern, re.X).match
NAMEDCOLOURS = {
# expanded named colors from SVG spc
'aliceblue': colors.HexColor('#f0f8ff'),
'antiquewhite': colors.HexColor('#faebd7'),
'aqua': colors.HexColor('#00ffff'),
'aquamarine': colors.HexColor('#7fffd4'),
'azure': colors.HexColor('#f0ffff'),
'beige': colors.HexColor('#f5f5dc'),
'bisque': colors.HexColor('#ffe4c4'),
'black': colors.HexColor('#000000'),
'blanchedalmond': colors.HexColor('#ffebcd'),
'blue': colors.HexColor('#0000ff'),
'blueviolet': colors.HexColor('#8a2be2'),
'brown': colors.HexColor('#a52a2a'),
'burlywood': colors.HexColor('#deb887'),
'cadetblue': colors.HexColor('#5f9ea0'),
'chartreuse': colors.HexColor('#7fff00'),
'chocolate': colors.HexColor('#d2691e'),
'coral': colors.HexColor('#ff7f50'),
'cornflowerblue': colors.HexColor('#6495ed'),
'cornsilk': colors.HexColor('#fff8dc'),
'crimson': colors.HexColor('#dc143c'),
'cyan': colors.HexColor('#00ffff'),
'darkblue': colors.HexColor('#00008b'),
'darkcyan': colors.HexColor('#008b8b'),
'darkgoldenrod': colors.HexColor('#b8860b'),
'darkgray': colors.HexColor('#a9a9a9'),
'darkgreen': colors.HexColor('#006400'),
'darkgrey': colors.HexColor('#a9a9a9'),
'darkkhaki': colors.HexColor('#bdb76b'),
'darkmagenta': colors.HexColor('#8b008b'),
'darkolivegreen': colors.HexColor('#556b2f'),
'darkorange': colors.HexColor('#ff8c00'),
'darkorchid': colors.HexColor('#9932cc'),
'darkred': colors.HexColor('#8b0000'),
'darksalmon': colors.HexColor('#e9967a'),
'darkseagreen': colors.HexColor('#8fbc8b'),
'darkslateblue': colors.HexColor('#483d8b'),
'darkslategray': colors.HexColor('#2f4f4f'),
'darkslategrey': colors.HexColor('#2f4f4f'),
'darkturquoise': colors.HexColor('#00ced1'),
'darkviolet': colors.HexColor('#9400d3'),
'deeppink': colors.HexColor('#ff1493'),
'deepskyblue': colors.HexColor('#00bfff'),
'dimgray': colors.HexColor('#696969'),
'dimgrey': colors.HexColor('#696969'),
'dodgerblue': colors.HexColor('#1e90ff'),
'firebrick': colors.HexColor('#b22222'),
'floralwhite': colors.HexColor('#fffaf0'),
'forestgreen': colors.HexColor('#228b22'),
'fuchsia': colors.HexColor('#ff00ff'),
'gainsboro': colors.HexColor('#dcdcdc'),
'ghostwhite': colors.HexColor('#f8f8ff'),
'gold': colors.HexColor('#ffd700'),
'goldenrod': colors.HexColor('#daa520'),
'gray': colors.HexColor('#808080'),
'green': colors.HexColor('#008000'),
'greenyellow': colors.HexColor('#adff2f'),
'grey': colors.HexColor('#808080'),
'honeydew': colors.HexColor('#f0fff0'),
'hotpink': colors.HexColor('#ff69b4'),
'indianred': colors.HexColor('#cd5c5c'),
'indigo': colors.HexColor('#4b0082'),
'ivory': colors.HexColor('#fffff0'),
'khaki': colors.HexColor('#f0e68c'),
'lavender': colors.HexColor('#e6e6fa'),
'lavenderblush': colors.HexColor('#fff0f5'),
'lawngreen': colors.HexColor('#7cfc00'),
'lemonchiffon': colors.HexColor('#fffacd'),
'lightblue': colors.HexColor('#add8e6'),
'lightcoral': colors.HexColor('#f08080'),
'lightcyan': colors.HexColor('#e0ffff'),
'lightgoldenrodyellow': colors.HexColor('#fafad2'),
'lightgray': colors.HexColor('#d3d3d3'),
'lightgreen': colors.HexColor('#90ee90'),
'lightgrey': colors.HexColor('#d3d3d3'),
'lightpink': colors.HexColor('#ffb6c1'),
'lightsalmon': colors.HexColor('#ffa07a'),
'lightseagreen': colors.HexColor('#20b2aa'),
'lightskyblue': colors.HexColor('#87cefa'),
'lightslategray': colors.HexColor('#778899'),
'lightslategrey': colors.HexColor('#778899'),
'lightsteelblue': colors.HexColor('#b0c4de'),
'lightyellow': colors.HexColor('#ffffe0'),
'lime': colors.HexColor('#00ff00'),
'limegreen': colors.HexColor('#32cd32'),
'linen': colors.HexColor('#faf0e6'),
'magenta': colors.HexColor('#ff00ff'),
'maroon': colors.HexColor('#800000'),
'mediumaquamarine': colors.HexColor('#66cdaa'),
'mediumblue': colors.HexColor('#0000cd'),
'mediumorchid': colors.HexColor('#ba55d3'),
'mediumpurple': colors.HexColor('#9370db'),
'mediumseagreen': colors.HexColor('#3cb371'),
'mediumslateblue': colors.HexColor('#7b68ee'),
'mediumspringgreen': colors.HexColor('#00fa9a'),
'mediumturquoise': colors.HexColor('#48d1cc'),
'mediumvioletred': colors.HexColor('#c71585'),
'midnightblue': colors.HexColor('#191970'),
'mintcream': colors.HexColor('#f5fffa'),
'mistyrose': colors.HexColor('#ffe4e1'),
'moccasin': colors.HexColor('#ffe4b5'),
'navajowhite': colors.HexColor('#ffdead'),
'navy': colors.HexColor('#000080'),
'oldlace': colors.HexColor('#fdf5e6'),
'olive': colors.HexColor('#808000'),
'olivedrab': colors.HexColor('#6b8e23'),
'orange': colors.HexColor('#ffa500'),
'orangered': colors.HexColor('#ff4500'),
'orchid': colors.HexColor('#da70d6'),
'palegoldenrod': colors.HexColor('#eee8aa'),
'palegreen': colors.HexColor('#98fb98'),
'paleturquoise': colors.HexColor('#afeeee'),
'palevioletred': colors.HexColor('#db7093'),
'papayawhip': colors.HexColor('#ffefd5'),
'peachpuff': colors.HexColor('#ffdab9'),
'peru': colors.HexColor('#cd853f'),
'pink': colors.HexColor('#ffc0cb'),
'plum': colors.HexColor('#dda0dd'),
'powderblue': colors.HexColor('#b0e0e6'),
'purple': colors.HexColor('#800080'),
'red': colors.HexColor('#ff0000'),
'rosybrown': colors.HexColor('#bc8f8f'),
'royalblue': colors.HexColor('#4169e1'),
'saddlebrown': colors.HexColor('#8b4513'),
'salmon': colors.HexColor('#fa8072'),
'sandybrown': colors.HexColor('#f4a460'),
'seagreen': colors.HexColor('#2e8b57'),
'seashell': colors.HexColor('#fff5ee'),
'sienna': colors.HexColor('#a0522d'),
'silver': colors.HexColor('#c0c0c0'),
'skyblue': colors.HexColor('#87ceeb'),
'slateblue': colors.HexColor('#6a5acd'),
'slategray': colors.HexColor('#708090'),
'slategrey': colors.HexColor('#708090'),
'snow': colors.HexColor('#fffafa'),
'springgreen': colors.HexColor('#00ff7f'),
'steelblue': colors.HexColor('#4682b4'),
'tan': colors.HexColor('#d2b48c'),
'teal': colors.HexColor('#008080'),
'thistle': colors.HexColor('#d8bfd8'),
'tomato': colors.HexColor('#ff6347'),
'turquoise': colors.HexColor('#40e0d0'),
'violet': colors.HexColor('#ee82ee'),
'wheat': colors.HexColor('#f5deb3'),
'white': colors.HexColor('#ffffff'),
'whitesmoke': colors.HexColor('#f5f5f5'),
'yellow': colors.HexColor('#ffff00'),
'yellowgreen': colors.HexColor('#9acd32'),
}
def parseColor(color):
"""
Convert SVG color to reportlab color
"""
if color == 'none':
return None
elif color == 'currentColor':
return "currentColor"
elif color == 'transparent':
return colors.Color(0., 0., 0., 0.)
match = color_match(color)
if match is None:
raise SVGError("Not a valid color definition: '%s'" % color)
info = match.groupdict()
if info['named'] is not None:
if color not in NAMEDCOLOURS:
raise SVGError("Not a valid named color: '%s'" % color)
return NAMEDCOLOURS[color]
elif info['hex'] is not None:
return colors.HexColor(color)
elif info['hexshort'] is not None:
r = 2*info['hexshort_r']
g = 2*info['hexshort_g']
b = 2*info['hexshort_b']
return colors.HexColor('#%s%s%s' % (r,g,b))
elif info['rgbint'] is not None:
r = int(info['rgbint_r'])
g = int(info['rgbint_g'])
b = int(info['rgbint_b'])
if r > 255 or g > 255 or b > 255:
raise SVGError("RGB value outside range: '%s'" % color)
return colors.Color(r/255., g/255., b/255.)
elif info['rgb'] is not None:
r = float(info['rgb_r'])
g = float(info['rgb_g'])
b = float(info['rgb_b'])
if r > 100 or g > 100 or b > 100:
raise SVGError("RGB value outside range: '%s'" % color)
return colors.Color(r/100., g/100., b/100.)
class SVGStyle(Lexer):
"""
Break SVG inline style into tokens
"""
name = object()
value = object()
delimiter = object()
comment = object()
lexicon = (
(delimiter, r'[ :;\n]'),
(comment, r'/\*.+\*/'),
(name, r'[\w\-#]+?(?=:)'),
(value, r'[\w\-#\.\(\)%,][\w \-#\.\(\)%,]*?(?=[;])'),
)
ignore = frozenset((delimiter, comment))
def __init__(self):
Lexer.__init__(self)
def parse(self, text):
"""
Parse a string of SVG <path> data.
"""
toks = self.lex(text + ';')
styles = {}
while True:
token, value = next(toks)
if token == EOF:
break
stylename = value.rstrip(':')
token, value = next(toks)
if token == EOF:
raise SVGError('expected value in style definition')
if stylename in styles:
raise SVGError('style redefined')
styles[stylename] = value
return styles
parseStyle = SVGStyle()
class SVGTransform(Lexer):
"""
Break SVG transform into tokens.
"""
numfloat = object()
numint = object()
string = object()
skip = object()
numbers = frozenset((numfloat, numint))
lexicon = (
(numfloat, Lexer.Float),
(numint, Lexer.Int),
(string, r'\w+'),
(skip, r'[\(\), \n]'),
)
ignore = frozenset((skip,))
callbacks = {
numfloat: lambda self, value: float(value),
numint: lambda self, value: float(value)
}
def __init__(self):
Lexer.__init__(self)
def assertion(self, condition, msg = ''):
if not condition:
raise SVGError(msg)
def iterparse(self, text):
"""
Parse a string of SVG transform data.
"""
assertion = self.assertion
toks = self.lex(text)
numbers = self.numbers
string = self.string
token, value = next(toks)
while token != EOF:
assertion(token is string, 'Expected string')
transform = value
if transform == 'matrix':
token, a = next(toks)
assertion(token in numbers, 'Expected number')
token, b = next(toks)
assertion(token in numbers, 'Expected number')
token, c = next(toks)
assertion(token in numbers, 'Expected number')
token, d = next(toks)
assertion(token in numbers, 'Expected number')
token, e = next(toks)
assertion(token in numbers, 'Expected number')
token, f = next(toks)
assertion(token in numbers, 'Expected number')
yield (transform, (a, b, c, d, e, f))
elif transform == 'translate':
token, tx = next(toks)
assertion(token in numbers, 'Expected number')
token, value = next(toks)
ty = value
if token not in numbers:
ty = 0.
yield (transform, (tx, ty))
if token not in numbers:
continue
elif transform == 'scale':
token, sx = next(toks)
assertion(token in numbers, 'Expected number')
token, value = next(toks)
sy = value
if token not in numbers:
sy = sx
yield (transform, (sx, sy))
if token not in numbers:
continue
elif transform == 'rotate':
token, angle = next(toks)
assertion(token in numbers, 'Expected number')
token, value = next(toks)
cx = value
if token in numbers:
token, value = next(toks)
assertion(token in numbers, 'Expected number')
cy = value
yield (transform, (angle, (cx, cy)))
else:
yield (transform, (angle, None))
continue
elif transform == 'skewX' or transform == 'skewY':
token, value = next(toks)
angle = value
assertion(token in numbers, 'Expected number')
yield (transform, (angle,))
else:
raise SVGError("unknown transform '%s'" % transform)
# fetch next token
token, value = next(toks)
parseTransform = SVGTransform()
class SVGPath(Lexer):
"""
Break SVG path data into tokens.
The SVG spec requires that tokens are greedy.
This lexer relies on Python's regexes defaulting to greediness.
"""
numfloat = object()
numint = object()
numexp = object()
string = object()
skip = object
lexicon = (
(numfloat, Lexer.Float),
(numint, Lexer.Int),
(numexp, r'(?:[Ee][-\+]?\d+)'),
(string, r'[AaCcHhLlMmQqSsTtVvZz]'),
(skip, r'[, \n]'),
)
ignore = frozenset((skip,))
callbacks = {
numfloat: lambda self,value: float(value),
numint: lambda self,value: float(value),
numexp: lambda self,value: float('1.'+value)
}
numbers = frozenset((numfloat, numint, numexp))
def __init__(self):
Lexer.__init__(self)
def assertion(self, condition, msg=''):
if not condition:
raise SVGError(msg)
def iterparse(self, text):
"""
Parse a string of SVG <path> data.
"""
assertion = self.assertion
numbers = self.numbers
string = self.string
toks = self.lex(text)
token, value = next(toks)
while token != EOF:
assertion(token is string, 'Expected string in path data')
cmd = value
CMD = value.upper()
# closePath
if CMD in 'Z':
token, value = next(toks)
yield (cmd, (None,))
# moveTo, lineTo, curve, smoothQuadraticBezier, quadraticBezier, smoothCurve
elif CMD in 'CMLTQS':
coords = []
token, value = next(toks)
while token in numbers:
last = value
token, value = next(toks)
assertion(token in numbers, 'Expected number in path data')
coords.append((last, value))
token, value = next(toks)
if CMD == 'C':
assertion(len(coords) % 3 == 0, 'Expected coordinate triplets in path data')
yield (cmd, tuple(coords))
# horizontalLine or verticalLine
elif CMD in 'HVhv':
coords = []
token, value = next(toks)
assertion(token in numbers, 'Expected number')
while token in numbers:
coords.append(value)
token, value = next(toks)
yield (cmd, tuple(coords))
# ellipticalArc
elif CMD == 'A':
token, rx = next(toks)
#assertion(token in numbers and value > 0, 'expected positive number in path data')
rx = value
token, ry = next(toks)
#assertion(token in numbers and ry > 0, 'expected positive number in path data')
token, rotation = next(toks)
#assertion(token in numbers, 'expected number in path data')
token, largearc = next(toks)
#assertion(token is int and largearc in (0,1), 'expected 0 or 1 in path data')
token, sweeparc = next(toks)
#assertion(token is int and sweeparc in (0,1), 'expected 0 or 1 in path data')
token, x = next(toks)
#assertion(token in numbers, 'expected number in path data')
token, y = next(toks)
#assertion(token in numbers, 'expected number in path data')
yield (cmd, ((rx,ry), rotation, largearc, sweeparc, (x,y)))
token, value = next(toks)
else:
raise SVGError("cmd '%s' in path data not supported" % cmd)
parsePath = SVGPath()
def parseDashArray(array):
if array == 'none':
return None
return list(map(parseLength, re.split('[ ,]+', array)))
def parseOpacity(value):
try:
opacity = float(value)
except ValueError:
raise SVGError('expected float value')
# clamp value
opacity = min(max(opacity, 0.), 1.)
return opacity
def parseAnchor(value):
if not value or value == 'none':
return 'start'
if value not in ('start', 'middle', 'end'):
raise SVGError("unknown '%s' alignment" % value)
return value
# map svg font names to reportlab names
FONTMAPPING = {
"sans-serif": "Helvetica",
"serif": "Times-Roman",
"monospace": "Courier"
}
# map svg style to repotlab attributes and converters
STYLES = {
"fill": ("fillColor", parseColor),
"stroke": ("strokeColor", parseColor),
"stroke-width": ("strokeWidth", parseLength),
"stroke-linejoin": ("strokeLineJoin", lambda style: {"miter":0, "round":1, "bevel":2}[style]),
"stroke-linecap": ("strokeLineCap", lambda style: {"butt":0, "round":1, "square":2}[style]),
"stroke-dasharray": ("strokeDashArray", parseDashArray),
"fill-opacity": ('fillOpacity', parseOpacity),
"stroke-opacity": ('strokeOpacity', parseOpacity),
"font-family": ("fontName", lambda name: FONTMAPPING.get(name, 'Helvetica')),
"font-size": ("fontSize", parseLength),
"text-anchor": ("textAnchor", parseAnchor),
}
STYLE_NAMES = frozenset(list(STYLES.keys()) + ['color',])
STYLES_FONT = frozenset(('font-family','font-size','text-anchor'))
class Renderer:
LINK = '{http://www.w3.org/1999/xlink}href'
SVG_NS = '{http://www.w3.org/2000/svg}'
SVG_ROOT = SVG_NS + 'svg'
SVG_A = SVG_NS + 'a'
SVG_G = SVG_NS + 'g'
SVG_TITLE = SVG_NS + 'title'
SVG_DESC = SVG_NS + 'desc'
SVG_DEFS = SVG_NS + 'defs'
SVG_SYMBOL = SVG_NS + 'symbol'
SVG_USE = SVG_NS + 'use'
SVG_RECT = SVG_NS + 'rect'
SVG_CIRCLE = SVG_NS + 'circle'
SVG_ELLIPSE = SVG_NS + 'ellipse'
SVG_LINE = SVG_NS + 'line'
SVG_POLYLINE = SVG_NS + 'polyline'
SVG_POLYGON = SVG_NS + 'polygon'
SVG_PATH = SVG_NS + 'path'
SVG_TEXT = SVG_NS + 'text'
SVG_TSPAN = SVG_NS + 'tspan'
SVG_IMAGE = SVG_NS + 'image'
SVG_NODES = frozenset((
SVG_ROOT, SVG_A, SVG_G, SVG_TITLE, SVG_DESC, SVG_DEFS, SVG_SYMBOL,
SVG_USE, SVG_RECT, SVG_CIRCLE, SVG_ELLIPSE, SVG_LINE, SVG_POLYLINE,
SVG_POLYGON, SVG_PATH, SVG_TEXT, SVG_TSPAN, SVG_IMAGE
))
SKIP_NODES = frozenset((SVG_TITLE, SVG_DESC, SVG_DEFS, SVG_SYMBOL))
PATH_NODES = frozenset((SVG_RECT, SVG_CIRCLE, SVG_ELLIPSE, SVG_LINE,
SVG_POLYLINE, SVG_POLYGON, SVG_PATH, SVG_TEXT))
def __init__(self, filename):
self.filename = filename
self.level = 0
self.styles = {}
self.mainGroup = Group()
self.drawing = None
self.root = None
def render(self, node, parent=None):
if parent is None:
parent = self.mainGroup
# ignore if display = none
display = node.get('display')
if display == "none":
return
if node.tag == self.SVG_ROOT:
self.level += 1
if not self.drawing is None:
raise SVGError('drawing already created!')
self.root = node
# default styles
style = {
'color':'none',
'fill':'none',
'stroke':'none',
'font-family':'Helvetica',
'font-size':'12'
}
self.styles[self.level] = style
# iterate children
for child in node:
self.render(child, self.mainGroup)
# create drawing
width = node.get('width', '100%')
height = node.get('height', '100%')
if node.get("viewBox"):
try:
minx, miny, width, height = node.get("viewBox").split()
except ValueError:
raise SVGError("viewBox values not valid")
if width.endswith('%') and height.endswith('%'):
# handle relative size
wscale = parseLength(width) / 100.
hscale = parseLength(height) / 100.
xL,yL,xH,yH = self.mainGroup.getBounds()
self.drawing = Drawing(xH*wscale + xL, yH*hscale + yL)
else:
self.drawing = Drawing(parseLength(width), parseLength(height))
height = self.drawing.height
self.mainGroup.scale(1, -1)
self.mainGroup.translate(0, -height)
self.drawing.add(self.mainGroup)
self.level -= 1
return self.drawing
elif node.tag in (self.SVG_G, self.SVG_A):
self.level += 1
# set this levels style
style = self.styles[self.level - 1].copy()
style = self.nodeStyle(node, style)
self.styles[self.level] = style
group = Group()
# iterate children
for child in node:
self.render(child, group)
parent.add(group)
transforms = node.get('transform')
if transforms:
for op in parseTransform.iterparse(transforms):
self.applyTransformOnGroup(group, op)
self.level -= 1
elif node.tag == self.SVG_USE:
self.level += 1
# set this levels style
style = self.styles[self.level - 1].copy()
style = self.nodeStyle(node, style)
self.styles[self.level] = style
group = Group()
# link id
link_id = node.get(self.LINK).lstrip('#')
# find linked node in defs or symbol section
target = None
for defs in self.root.getiterator(self.SVG_DEFS):
for element in defs:
if element.get('id') == link_id:
target = element
break
if target is None:
for defs in self.root.getiterator(self.SVG_SYMBOL):
for element in defs:
if element.get('id') == link_id:
target = element
break
if target is None:
msg = "Could not find use node '%s'" % link_id
raise SVGError(msg)
self.render(target, group)
parent.add(group)
# apply transform
transforms = node.get('transform')
if transforms:
for op in parseTransform.iterparse(transforms):
self.applyTransformOnGroup(group, op)
# apply 'x' and 'y' attribute as translation of defs object
if node.get('x') or node.get('y'):
dx = parseLength(node.get('x','0'))
dy = parseLength(node.get('y','0'))
self.applyTransformOnGroup(group, ('translate', (dx,dy)))
self.level -= 1
elif node.tag == self.SVG_LINE:
# get coordinates
x1 = parseLength(node.get('x1', '0'))
y1 = parseLength(node.get('y1', '0'))
x2 = parseLength(node.get('x2', '0'))
y2 = parseLength(node.get('y2', '0'))
shape = Line(x1, y1, x2, y2)
self.addShape(parent, node, shape)
elif node.tag == self.SVG_RECT:
# get coordinates
x = parseLength(node.get('x', '0'))
y = parseLength(node.get('y', '0'))
width = parseLength(node.get('width'))
height = parseLength(node.get('height'))
rx = parseLength(node.get('rx', '0'))
ry = parseLength(node.get('ry', '0'))
shape = Rect(x, y, width, height, rx=rx, ry=ry)
self.addShape(parent, node, shape)
elif node.tag == self.SVG_CIRCLE:
cx = parseLength(node.get('cx', '0'))
cy = parseLength(node.get('cy', '0'))
r = parseLength(node.get('r'))
if r > 0.:
shape = Circle(cx, cy, r)
self.addShape(parent, node, shape)
elif node.tag == self.SVG_ELLIPSE:
cx = parseLength(node.get('cx', '0'))
cy = parseLength(node.get('cy', '0'))
rx = parseLength(node.get('rx'))
ry = parseLength(node.get('ry'))
if rx > 0. and ry > 0.:
shape = Ellipse(cx, cy, rx, ry)
self.addShape(parent, node, shape)
elif node.tag == self.SVG_POLYLINE:
# convert points
points = node.get('points').strip()
if len(points) == 0:
return
points = list(map(parseLength, re.split('[ ,]+', points)))
# Need to use two shapes, because standard RLG polylines
# do not support filling...
group = Group()
shape = Polygon(points)
self.applyStyleToShape(shape, node)
shape.strokeColor = None
group.add(shape)
shape = PolyLine(points)
self.applyStyleToShape(shape, node)
group.add(shape)
self.addShape(parent, node, group)
elif node.tag == self.SVG_POLYGON:
# convert points
points = node.get('points').strip()
if len(points) == 0:
return
points = list(map(parseLength, re.split('[ ,]+', points)))
shape = Polygon(points)
self.addShape(parent, node, shape)
elif node.tag == self.SVG_IMAGE:
x = parseLength(node.get('x', '0'))
y = parseLength(node.get('y', '0'))
width = parseLength(node.get('width', '0'))
height = parseLength(node.get('height', '0'))
# link id
link_id = node.get(self.LINK)
filename = os.path.join(os.path.dirname(self.filename), link_id)
shape = Image(x, y, width, height, filename)
self.addShape(parent, node, shape)
elif node.tag == self.SVG_TEXT:
# Todo:
# - rotation not handled
# - baseshift not handled
# - embedded span node not handled