Debian Codegraph @

svglib/svglib.py

raw symbols SCIP
1 #!/usr/bin/env python
2 """A library for reading and converting SVG.
3
4 This is a converter from SVG to RLG (ReportLab Graphics) drawings.
5 It converts mainly basic shapes, paths and simple text. The intended
6 usage is either as module within other projects:
7
8 from svglib.svglib import svg2rlg
9 drawing = svg2rlg("foo.svg")
10
11 or from the command-line where it is usable as an SVG to PDF converting
12 tool named sv2pdf (which should also handle SVG files compressed with
13 gzip and extension .svgz).
14 """
15
16 import base64
17 import copy
18 import gzip
19 import itertools
20 import logging
21 import os
22 import pathlib
23 import re
24 import tempfile
25 import shlex
26 import shutil
27 from collections import defaultdict, namedtuple
28
29 from reportlab.pdfbase.pdfmetrics import stringWidth
30 from reportlab.pdfgen.canvas import FILL_EVEN_ODD, FILL_NON_ZERO
31 from reportlab.pdfgen.pdfimages import PDFImage
32 from reportlab.graphics.shapes import (
33 _CLOSEPATH, Circle, Drawing, Ellipse, Group, Image, Line, Path, PolyLine,
34 Polygon, Rect, SolidShape, String,
35 )
36 from reportlab.lib import colors
37 from reportlab.lib.units import pica, toLength
38 from reportlab.lib.utils import haveImages
39
40 try:
41 from reportlab.graphics.transform import mmult
42 except ImportError:
43 # Before Reportlab 3.5.61
44 from reportlab.graphics.shapes import mmult
45
46 from lxml import etree
47 import cssselect2
48 import tinycss2
49
50 from .utils import (
51 bezier_arc_from_end_points, convert_quadratic_to_cubic_path,
52 normalise_svg_path,
53 )
54
55 from .fonts import (
56 get_global_font_map, DEFAULT_FONT_NAME, DEFAULT_FONT_WEIGHT, DEFAULT_FONT_STYLE,
57 DEFAULT_FONT_SIZE,
58 )
59
60 # To keep backward compatibility, since those functions where previously part of the svglib module
61 from .fonts import (
62 register_font as _fonts_register_font, find_font as _fonts_find_font,
63 )
64
65
66 def register_font(font_name, font_path=None, weight='normal', style='normal', rlgFontName=None):
67 return _fonts_register_font(font_name, font_path, weight, style, rlgFontName)
68
69
70 def find_font(font_name, weight='normal', style='normal'):
71 return _fonts_find_font(font_name, weight, style)
72
73
74 __version__ = '1.5.1'
75 __license__ = 'LGPL 3'
76 __author__ = 'Dinu Gherman'
77 __date__ = '2023-01-07'
78
79 XML_NS = 'http://www.w3.org/XML/1998/namespace'
80
81 # A sentinel to identify a situation where a node reference a fragment not yet defined.
82 DELAYED = object()
83
84 logger = logging.getLogger(__name__)
85
86 Box = namedtuple('Box', ['x', 'y', 'width', 'height'])
87
88 split_whitespace = re.compile(r'[^ \t\r\n\f]+').findall
89
90
91 class NoStrokePath(Path):
92 """
93 This path object never gets a stroke width whatever the properties it's
94 getting assigned.
95 """
96 def __init__(self, *args, **kwargs):
97 copy_from = kwargs.pop('copy_from', None)
98 super().__init__(*args, **kwargs)
99 if copy_from:
100 self.__dict__.update(copy.deepcopy(copy_from.__dict__))
101
102 def getProperties(self, *args, **kwargs):
103 # __getattribute__ wouldn't suit, as RL is directly accessing self.__dict__
104 props = super().getProperties(*args, **kwargs)
105 if 'strokeWidth' in props:
106 props['strokeWidth'] = 0
107 if 'strokeColor' in props:
108 props['strokeColor'] = None
109 return props
110
111
112 class ClippingPath(Path):
113 def __init__(self, *args, **kwargs):
114 copy_from = kwargs.pop('copy_from', None)
115 Path.__init__(self, *args, **kwargs)
116 if copy_from:
117 self.__dict__.update(copy.deepcopy(copy_from.__dict__))
118 self.isClipPath = 1
119
120 def getProperties(self, *args, **kwargs):
121 props = Path.getProperties(self, *args, **kwargs)
122 if 'fillColor' in props:
123 props['fillColor'] = None
124 if 'strokeColor' in props:
125 props['strokeColor'] = None
126 return props
127
128
129 class CSSMatcher(cssselect2.Matcher):
130 def add_styles(self, style_content):
131 rules = tinycss2.parse_stylesheet(
132 style_content, skip_comments=True, skip_whitespace=True
133 )
134
135 for rule in rules:
136 if not rule.prelude or rule.type == 'at-rule':
137 continue
138 selectors = cssselect2.compile_selector_list(rule.prelude)
139 selector_string = tinycss2.serialize(rule.prelude)
140 content_dict = {
141 attr.split(':')[0].strip(): attr.split(':')[1].strip()
142 for attr in tinycss2.serialize(rule.content).split(';')
143 if ':' in attr
144 }
145 payload = (selector_string, content_dict)
146 for selector in selectors:
147 self.add_selector(selector, payload)
148
149
150 # Attribute converters (from SVG to RLG)
151
152 class AttributeConverter:
153 "An abstract class to locate and convert attributes in a DOM instance."
154
155 def __init__(self):
156 self.css_rules = None
157 self.main_box = None
158
159 def set_box(self, main_box):
160 self.main_box = main_box
161
162 def parseMultiAttributes(self, line):
163 """Try parsing compound attribute string.
164
165 Return a dictionary with single attributes in 'line'.
166 """
167
168 attrs = line.split(';')
169 attrs = [a.strip() for a in attrs]
170 attrs = filter(lambda a: len(a) > 0, attrs)
171
172 new_attrs = {}
173 for a in attrs:
174 k, v = a.split(':')
175 k, v = [s.strip() for s in (k, v)]
176 new_attrs[k] = v
177
178 return new_attrs
179
180 def findAttr(self, svgNode, name):
181 """Search an attribute with some name in some node or above.
182
183 First the node is searched, then its style attribute, then
184 the search continues in the node's parent node. If no such
185 attribute is found, '' is returned.
186 """
187
188 # This needs also to lookup values like "url(#SomeName)"...
189
190 if not svgNode.attrib.get('__rules_applied', False):
191 # Apply global styles...
192 if self.css_rules is not None:
193 svgNode.apply_rules(self.css_rules)
194 # ...and locally defined
195 if svgNode.attrib.get("style"):
196 attrs = self.parseMultiAttributes(svgNode.attrib.get("style"))
197 for key, val in attrs.items():
198 # lxml nodes cannot accept attributes starting with '-'
199 if not key.startswith('-'):
200 svgNode.attrib[key] = val
201 svgNode.attrib['__rules_applied'] = '1'
202
203 attr_value = svgNode.attrib.get(name, '').strip()
204
205 if attr_value and attr_value != "inherit":
206 return attr_value
207 if svgNode.parent is not None:
208 return self.findAttr(svgNode.parent, name)
209 return ''
210
211 def getAllAttributes(self, svgNode):
212 "Return a dictionary of all attributes of svgNode or those inherited by it."
213
214 dict = {}
215
216 if node_name(svgNode.getparent()) == 'g':
217 dict.update(self.getAllAttributes(svgNode.getparent()))
218
219 style = svgNode.attrib.get("style")
220 if style:
221 d = self.parseMultiAttributes(style)
222 dict.update(d)
223
224 for key, value in svgNode.attrib.items():
225 if key != "style":
226 dict[key] = value
227
228 return dict
229
230 def id(self, svgAttr):
231 "Return attribute as is."
232 return svgAttr
233
234 def convertTransform(self, svgAttr):
235 """Parse transform attribute string.
236
237 E.g. "scale(2) translate(10,20)"
238 -> [("scale", 2), ("translate", (10,20))]
239 """
240
241 line = svgAttr.strip()
242
243 ops = line[:]
244 brackets = []
245 indices = []
246 for i, lin in enumerate(line):
247 if lin in "()":
248 brackets.append(i)
249 for i in range(0, len(brackets), 2):
250 bi, bj = brackets[i], brackets[i+1]
251 subline = line[bi+1:bj]
252 subline = subline.strip()
253 subline = subline.replace(',', ' ')
254 subline = re.sub("[ ]+", ',', subline)
255 try:
256 if ',' in subline:
257 indices.append(tuple(float(num) for num in subline.split(',')))
258 else:
259 indices.append(float(subline))
260 except ValueError:
261 continue
262 ops = ops[:bi] + ' '*(bj-bi+1) + ops[bj+1:]
263 ops = ops.replace(',', ' ').split()
264
265 if len(ops) != len(indices):
266 logger.warning("Unable to parse transform expression %r", svgAttr)
267 return []
268
269 result = []
270 for i, op in enumerate(ops):
271 result.append((op, indices[i]))
272
273 return result
274
275
276 class Svg2RlgAttributeConverter(AttributeConverter):
277 "A concrete SVG to RLG attribute converter."
278
279 def __init__(self, color_converter=None, font_map=None):
280 super().__init__()
281 self.color_converter = color_converter or self.identity_color_converter
282 self._font_map = font_map or get_global_font_map()
283
284 @staticmethod
285 def identity_color_converter(c):
286 return c
287
288 @staticmethod
289 def split_attr_list(attr):
290 return shlex.split(attr.strip().replace(',', ' '))
291
292 def convertLength(self, svgAttr, em_base=DEFAULT_FONT_SIZE, attr_name=None, default=0.0):
293 "Convert length to points."
294
295 text = svgAttr.replace(',', ' ').strip()
296 if not text:
297 return default
298 if ' ' in text:
299 # Multiple length values, returning a list
300 return [
301 self.convertLength(val, em_base=em_base, attr_name=attr_name, default=default)
302 for val in self.split_attr_list(text)
303 ]
304
305 if text.endswith('%'):
306 if self.main_box is None:
307 logger.error("Unable to resolve percentage unit without a main box")
308 return float(text[:-1])
309 if attr_name is None:
310 logger.error("Unable to resolve percentage unit without knowing the node name")
311 return float(text[:-1])
312 if attr_name in ('x', 'cx', 'x1', 'x2', 'width'):
313 full = self.main_box.width
314 elif attr_name in ('y', 'cy', 'y1', 'y2', 'height'):
315 full = self.main_box.height
316 else:
317 logger.error("Unable to detect if node %r is width or height", attr_name)
318 return float(text[:-1])
319 return float(text[:-1]) / 100 * full
320 elif text.endswith("pc"):
321 return float(text[:-2]) * pica
322 elif text.endswith("pt"):
323 return float(text[:-2]) * 1.25
324 elif text.endswith("em"):
325 return float(text[:-2]) * em_base
326 elif text.endswith("px"):
327 return float(text[:-2])
328 elif text.endswith("ex"):
329 # The x-height of the text must be assumed to be 0.5em tall when the
330 # text cannot be measured.
331 return float(text[:-2]) * em_base / 2
332 elif text.endswith("ch"):
333 # The advance measure of the "0" glyph must be assumed to be 0.5em
334 # wide when the text cannot be measured.
335 return float(text[:-2]) * em_base / 2
336
337 text = text.strip()
338 length = toLength(text) # this does the default measurements such as mm and cm
339
340 return length
341
342 def convertLengthList(self, svgAttr):
343 """Convert a list of lengths."""
344 return [self.convertLength(a) for a in self.split_attr_list(svgAttr)]
345
346 def convertOpacity(self, svgAttr):
347 return float(svgAttr)
348
349 def convertFillRule(self, svgAttr):
350 return {
351 'nonzero': FILL_NON_ZERO,
352 'evenodd': FILL_EVEN_ODD,
353 }.get(svgAttr, '')
354
355 def convertColor(self, svgAttr):
356 "Convert string to a RL color object."
357
358 # This needs also to lookup values like "url(#SomeName)"...
359
360 text = svgAttr
361 if not text or text == "none":
362 return None
363
364 if text == "currentColor":
365 return "currentColor"
366 if len(text) in (7, 9) and text[0] == '#':
367 color = colors.HexColor(text, hasAlpha=len(text) == 9)
368 elif len(text) == 4 and text[0] == '#':
369 color = colors.HexColor('#' + 2*text[1] + 2*text[2] + 2*text[3])
370 elif len(text) == 5 and text[0] == '#':
371 color = colors.HexColor(
372 '#' + 2*text[1] + 2*text[2] + 2*text[3] + 2*text[4], hasAlpha=True
373 )
374 else:
375 # Should handle pcmyk|cmyk|rgb|hsl values (including 'a' for alpha)
376 color = colors.cssParse(text)
377 if color is None:
378 # Test if text is a predefined color constant
379 try:
380 color = getattr(colors, text).clone()
381 except AttributeError:
382 pass
383 if color is None:
384 logger.warning("Can't handle color: %s", text)
385 else:
386 return self.color_converter(color)
387
388 def convertLineJoin(self, svgAttr):
389 return {"miter": 0, "round": 1, "bevel": 2}[svgAttr]
390
391 def convertLineCap(self, svgAttr):
392 return {"butt": 0, "round": 1, "square": 2}[svgAttr]
393
394 def convertDashArray(self, svgAttr):
395 strokeDashArray = self.convertLengthList(svgAttr)
396 return strokeDashArray
397
398 def convertDashOffset(self, svgAttr):
399 strokeDashOffset = self.convertLength(svgAttr)
400 return strokeDashOffset
401
402 def convertFontFamily(self, fontAttr, weightAttr='normal', styleAttr='normal'):
403 if not fontAttr:
404 return ''
405 # split the fontAttr in actual font family names
406 font_names = self.split_attr_list(fontAttr)
407
408 non_exact_matches = []
409 for font_name in font_names:
410 font_name, exact = self._font_map.find_font(font_name, weightAttr, styleAttr)
411 if exact:
412 return font_name
413 elif font_name:
414 non_exact_matches.append(font_name)
415 if non_exact_matches:
416 return non_exact_matches[0]
417 else:
418 logger.warning(
419 f"Unable to find a suitable font for 'font-family:{fontAttr}', "
420 f"weight:{weightAttr}, style:{styleAttr}"
421 )
422 return DEFAULT_FONT_NAME
423
424
425 class NodeTracker(cssselect2.ElementWrapper):
426 """An object wrapper keeping track of arguments to certain method calls.
427
428 Instances wrap an object and store all arguments to one special
429 method, getAttribute(name), in a list of unique elements, usedAttrs.
430 """
431
432 def __init__(self, *args, **kwargs):
433 super().__init__(*args, **kwargs)
434 self.usedAttrs = []
435
436 def __repr__(self):
437 return f'<NodeTracker for node {self.etree_element}>'
438
439 def getAttribute(self, name):
440 # add argument to the history, if not already present
441 if name not in self.usedAttrs:
442 self.usedAttrs.append(name)
443 # forward call to wrapped object
444 return self.etree_element.attrib.get(name, '')
445
446 def __getattr__(self, name):
447 # forward attribute access to wrapped object
448 return getattr(self.etree_element, name)
449
450 def apply_rules(self, rules):
451 matches = rules.match(self)
452 for match in matches:
453 attr_dict = match[3][1]
454 for attr, val in attr_dict.items():
455 try:
456 self.etree_element.attrib[attr] = val
457 except ValueError:
458 pass
459 # Set marker on the node to not apply rules more than once
460 self.etree_element.set('__rules_applied', '1')
461
462
463 class CircularRefError(Exception):
464 pass
465
466
467 class ExternalSVG:
468 def __init__(self, path, renderer):
469 self.root_node = load_svg_file(path)
470 self.renderer = SvgRenderer(
471 path, parent_svgs=renderer._parent_chain + [renderer.source_path]
472 )
473 self.rendered = False
474
475 def get_fragment(self, fragment):
476 if not self.rendered:
477 self.renderer.render(self.root_node)
478 self.rendered = True
479 return self.renderer.definitions.get(fragment)
480
481
482 # ## the main meat ###
483
484 class SvgRenderer:
485 """Renderer that renders an SVG file on a ReportLab Drawing instance.
486
487 This is the base class for walking over an SVG DOM document and
488 transforming it into a ReportLab Drawing instance.
489 """
490
491 def __init__(self, path, color_converter=None, parent_svgs=None, font_map=None):
492 self.source_path = path
493 self._parent_chain = parent_svgs or [] # To detect circular refs.
494 self.attrConverter = Svg2RlgAttributeConverter(
495 color_converter=color_converter, font_map=font_map
496 )
497 self.shape_converter = Svg2RlgShapeConverter(path, self.attrConverter)
498 self.handled_shapes = self.shape_converter.get_handled_shapes()
499 self.definitions = {}
500 self.waiting_use_nodes = defaultdict(list)
501 self._external_svgs = {}
502 self.attrConverter.css_rules = CSSMatcher()
503
504 def render(self, svg_node):
505 node = NodeTracker.from_xml_root(svg_node)
506 view_box = self.get_box(node, default_box=True)
507 # Knowing the main box is useful for percentage units
508 self.attrConverter.set_box(view_box)
509
510 main_group = self.renderSvg(node, outermost=True)
511 for xlink in self.waiting_use_nodes.keys():
512 logger.debug("Ignoring unavailable object width ID %r.", xlink)
513
514 main_group.translate(0 - view_box.x, -view_box.height - view_box.y)
515
516 width, height = self.shape_converter.convert_length_attrs(
517 svg_node, "width", "height", defaults=(view_box.width, view_box.height)
518 )
519 drawing = Drawing(width, height)
520 drawing.add(main_group)
521 return drawing
522
523 def renderNode(self, node, parent=None):
524 nid = node.getAttribute("id")
525 ignored = False
526 item = None
527 name = node_name(node)
528
529 clipping = self.get_clippath(node)
530 if name == "svg":
531 item = self.renderSvg(node)
532 parent.add(item)
533 elif name == "defs":
534 ignored = True # defs are handled in the initial rendering phase.
535 elif name == 'a':
536 item = self.renderA(node)
537 parent.add(item)
538 elif name == 'g':
539 display = node.getAttribute("display")
540 item = self.renderG(node, clipping=clipping)
541 if display != "none":
542 parent.add(item)
543 elif name == "style":
544 self.renderStyle(node)
545 elif name == "symbol":
546 item = self.renderSymbol(node)
547 # First time the symbol node is rendered, it should not be part of a group.
548 # It is only rendered to be part of definitions.
549 if node.attrib.get('_rendered'):
550 parent.add(item)
551 else:
552 node.set('_rendered', '1')
553 elif name == "use":
554 item = self.renderUse(node, clipping=clipping)
555 parent.add(item)
556 elif name == "clipPath":
557 item = self.renderG(node)
558 elif name in self.handled_shapes:
559 if name == 'image':
560 # We resolve the image target at renderer level because it can point
561 # to another SVG file or node which has to be rendered too.
562 target = self.xlink_href_target(node)
563 if target is None:
564 return
565 elif isinstance(target, tuple):
566 # This is SVG content needed to be rendered
567 gr = Group()
568 renderer, img_node = target
569 renderer.renderNode(img_node, parent=gr)
570 self.apply_node_attr_to_group(node, gr)
571 parent.add(gr)
572 return
573 else:
574 # Attaching target to node, so we can get it back in convertImage
575 node._resolved_target = target
576
577 item = self.shape_converter.convertShape(name, node, clipping)
578 display = node.getAttribute("display")
579 if item and display != "none":
580 parent.add(item)
581 else:
582 ignored = True
583 logger.debug("Ignoring node: %s", name)
584
585 if not ignored:
586 if nid and item:
587 self.definitions[nid] = node
588 # preserve id to keep track of svg objects
589 # and simplify further analyses of generated document
590 item.setProperties({'svgid': nid})
591 # labels are used in inkscape to name specific groups as layers
592 # preserving them simplify extraction of feature from the generated document
593 label_attrs = [v for k, v in node.attrib.items() if 'label' in k]
594 if len(label_attrs) == 1:
595 label, = label_attrs
596 item.setProperties({'label': label})
597 if nid in self.waiting_use_nodes.keys():
598 to_render = self.waiting_use_nodes.pop(nid)
599 for use_node, group in to_render:
600 self.renderUse(use_node, group=group)
601 self.print_unused_attributes(node)
602
603 def get_clippath(self, node):
604 """
605 Return the clipping Path object referenced by the node 'clip-path'
606 attribute, if any.
607 """
608 def get_shape_from_group(group):
609 for elem in group.contents:
610 if isinstance(elem, Group):
611 return get_shape_from_group(elem)
612 elif isinstance(elem, SolidShape):
613 return elem
614
615 def get_shape_from_node(node):
616 for child in node.iter_children():
617 if node_name(child) == 'path':
618 group = self.shape_converter.convertShape('path', child)
619 return group.contents[-1]
620 elif node_name(child) == 'use':
621 grp = self.renderUse(child)
622 return get_shape_from_group(grp)
623 elif node_name(child) == 'rect':
624 return self.shape_converter.convertRect(child)
625 else:
626 return get_shape_from_node(child)
627
628 clip_path = node.getAttribute('clip-path')
629 if not clip_path:
630 return
631 m = re.match(r'url\(#([^\)]*)\)', clip_path)
632 if not m:
633 return
634 ref = m.groups()[0]
635 if ref not in self.definitions:
636 logger.warning("Unable to find a clipping path with id %s", ref)
637 return
638
639 shape = get_shape_from_node(self.definitions[ref])
640 if isinstance(shape, Rect):
641 # It is possible to use a rect as a clipping path in an svg, so we
642 # need to convert it to a path for rlg.
643 x1, y1, x2, y2 = shape.getBounds()
644 cp = ClippingPath()
645 cp.moveTo(x1, y1)
646 cp.lineTo(x2, y1)
647 cp.lineTo(x2, y2)
648 cp.lineTo(x1, y2)
649 cp.closePath()
650 # Copy the styles from the rect to the clipping path.
651 copy_shape_properties(shape, cp)
652 return cp
653 elif isinstance(shape, Path):
654 return ClippingPath(copy_from=shape)
655 elif shape:
656 logging.error("Unsupported shape type %s for clipping", shape.__class__.__name__)
657
658 def print_unused_attributes(self, node):
659 if logger.level > logging.DEBUG:
660 return
661 all_attrs = self.attrConverter.getAllAttributes(node.etree_element).keys()
662 unused_attrs = [attr for attr in all_attrs if attr not in node.usedAttrs]
663 if unused_attrs:
664 logger.debug("Unused attrs: %s %s", node_name(node), unused_attrs)
665
666 def apply_node_attr_to_group(self, node, group):
667 getAttr = node.getAttribute
668 transform, x, y = map(getAttr, ("transform", "x", "y"))
669 if x or y:
670 transform += f" translate({x or 0}, {y or 0})"
671 if transform:
672 self.shape_converter.applyTransformOnGroup(transform, group)
673
674 def xlink_href_target(self, node, group=None):
675 """
676 Return either:
677 - a tuple (renderer, node) when the the xlink:href attribute targets
678 a vector file or node
679 - the path to an image file for any raster image targets
680 - None if any problem occurs
681 """
682 # Bare 'href' was introduced in SVG 2.
683 xlink_href = node.attrib.get('{http://www.w3.org/1999/xlink}href') or node.attrib.get('href')
684 if not xlink_href:
685 return None
686
687 # First handle any raster embedded image data
688 match = re.match(r"^data:image/(jpe?g|png);base64", xlink_href)
689 if match:
690 img_format = match.groups()[0]
691 image_data = base64.decodebytes(xlink_href[(match.span(0)[1] + 1):].encode('ascii'))
692 file_indicator, path = tempfile.mkstemp(suffix=f'.{img_format}')
693 with open(path, 'wb') as fh:
694 fh.write(image_data)
695 # Close temporary file (as opened by tempfile.mkstemp)
696 os.close(file_indicator)
697 # this needs to be removed later, not here...
698 # if exists(path): os.remove(path)
699 return path
700
701 # From here, we can assume this is a path.
702 if '#' in xlink_href:
703 iri, fragment = xlink_href.split('#', 1)
704 else:
705 iri, fragment = xlink_href, None
706
707 if iri:
708 # Only local relative paths are supported yet
709 if not isinstance(self.source_path, str):
710 logger.error(
711 "Unable to resolve image path %r as the SVG source is not "
712 "a file system path.",
713 iri
714 )
715 return None
716 path = os.path.normpath(os.path.join(os.path.dirname(self.source_path), iri))
717 if not os.access(path, os.R_OK):
718 return None
719 if path == self.source_path:
720 # Self-referencing, ignore the IRI part
721 iri = None
722
723 if iri:
724 if path.endswith('.svg'):
725 if path in self._parent_chain:
726 logger.error("Circular reference detected in file.")
727 raise CircularRefError()
728 if path not in self._external_svgs:
729 self._external_svgs[path] = ExternalSVG(path, self)
730 ext_svg = self._external_svgs[path]
731 if ext_svg.root_node is not None:
732 if fragment:
733 ext_frag = ext_svg.get_fragment(fragment)
734 if ext_frag is not None:
735 return ext_svg.renderer, ext_frag
736 else:
737 return ext_svg.renderer, NodeTracker.from_xml_root(ext_svg.root_node)
738 else:
739 # A raster image path
740 try:
741 # This will catch invalid images
742 PDFImage(path, 0, 0)
743 except OSError:
744 logger.error("Unable to read the image %s. Skipping...", path)
745 return None
746 return path
747
748 elif fragment:
749 # A pointer to an internal definition
750 if fragment in self.definitions:
751 return self, self.definitions[fragment]
752 else:
753 # The missing definition should appear later in the file
754 self.waiting_use_nodes[fragment].append((node, group))
755 return DELAYED
756
757 def renderTitle_(self, node):
758 # Main SVG title attr. could be used in the PDF document info field.
759 pass
760
761 def renderDesc_(self, node):
762 # Main SVG desc. attr. could be used in the PDF document info field.
763 pass
764
765 def get_box(self, svg_node, default_box=False):
766 view_box = svg_node.getAttribute("viewBox")
767 if view_box:
768 view_box = self.attrConverter.convertLengthList(view_box)
769 return Box(*view_box)
770 if default_box:
771 width, height = map(svg_node.getAttribute, ("width", "height"))
772 width, height = map(self.attrConverter.convertLength, (width, height))
773 return Box(0, 0, width, height)
774
775 def renderSvg(self, node, outermost=False):
776 _saved_preserve_space = self.shape_converter.preserve_space
777 self.shape_converter.preserve_space = node.getAttribute(f"{{{XML_NS}}}space") == 'preserve'
778 view_box = self.get_box(node, default_box=True)
779 _saved_box = self.attrConverter.main_box
780 if view_box:
781 self.attrConverter.set_box(view_box)
782
783 # Rendering all definition nodes first.
784 svg_ns = node.nsmap.get(None)
785 for def_node in node.iter_subtree():
786 if def_node.tag == (f'{{{svg_ns}}}defs' if svg_ns else 'defs'):
787 self.renderG(def_node)
788
789 group = Group()
790 for child in node.iter_children():
791 self.renderNode(child, group)
792 self.shape_converter.preserve_space = _saved_preserve_space
793 self.attrConverter.set_box(_saved_box)
794
795 # Translating
796 if not outermost:
797 x, y = self.shape_converter.convert_length_attrs(node, "x", "y")
798 if x or y:
799 group.translate(x or 0, y or 0)
800
801 # Scaling
802 if not view_box and outermost:
803 # Apply only the 'reverse' y-scaling (PDF 0,0 is bottom left)
804 group.scale(1, -1)
805 elif view_box:
806 x_scale, y_scale = 1, 1
807 width, height = self.shape_converter.convert_length_attrs(
808 node, "width", "height", defaults=(None,) * 2
809 )
810 if height is not None and view_box.height != height:
811 y_scale = height / view_box.height
812 if width is not None and view_box.width != width:
813 x_scale = width / view_box.width
814 group.scale(x_scale, y_scale * (-1 if outermost else 1))
815
816 return group
817
818 def renderG(self, node, clipping=None):
819 getAttr = node.getAttribute
820 id, transform = map(getAttr, ("id", "transform"))
821 gr = Group()
822 if clipping:
823 gr.add(clipping)
824 for child in node.iter_children():
825 self.renderNode(child, parent=gr)
826
827 if transform:
828 self.shape_converter.applyTransformOnGroup(transform, gr)
829
830 return gr
831
832 def renderStyle(self, node):
833 self.attrConverter.css_rules.add_styles(node.text or "")
834
835 def renderSymbol(self, node):
836 return self.renderG(node)
837
838 def renderA(self, node):
839 # currently nothing but a group...
840 # there is no linking info stored in shapes, maybe a group should?
841 return self.renderG(node)
842
843 def renderUse(self, node, group=None, clipping=None):
844 if group is None:
845 group = Group()
846
847 try:
848 item = self.xlink_href_target(node, group=group)
849 except CircularRefError:
850 node.parent.etree_element.remove(node.etree_element)
851 return group
852 if item is None:
853 return
854 elif isinstance(item, str):
855 logger.error("<use> nodes cannot reference bitmap image files")
856 return
857 elif item is DELAYED:
858 return group
859 else:
860 item = item[1] # [0] is the renderer, not used here.
861
862 if clipping:
863 group.add(clipping)
864 if len(node.getchildren()) == 0:
865 # Append a copy of the referenced node as the <use> child (if not already done)
866 node.append(copy.deepcopy(item))
867 self.renderNode(list(node.iter_children())[-1], parent=group)
868 self.apply_node_attr_to_group(node, group)
869 return group
870
871
872 class SvgShapeConverter:
873 """An abstract SVG shape converter.
874
875 Implement subclasses with methods named 'convertX(node)', where
876 'X' should be the capitalised name of an SVG node element for
877 shapes, like 'Rect', 'Circle', 'Line', etc.
878
879 Each of these methods should return a shape object appropriate
880 for the target format.
881 """
882 def __init__(self, path, attrConverter=None):
883 self.attrConverter = attrConverter or Svg2RlgAttributeConverter()
884 self.svg_source_file = path
885 self.preserve_space = False
886
887 @classmethod
888 def get_handled_shapes(cls):
889 """Dynamically determine a list of handled shape elements based on
890 convert<shape> method existence.
891 """
892 return [key[7:].lower() for key in dir(cls) if key.startswith('convert')]
893
894
895 class Svg2RlgShapeConverter(SvgShapeConverter):
896 """Converter from SVG shapes to RLG (ReportLab Graphics) shapes."""
897
898 def convertShape(self, name, node, clipping=None):
899 method_name = f"convert{name.capitalize()}"
900 shape = getattr(self, method_name)(node)
901 if not shape:
902 return
903 if name not in ('path', 'polyline', 'text'):
904 # Only apply style where the convert method did not apply it.
905 self.applyStyleOnShape(shape, node)
906 transform = node.getAttribute("transform")
907 if not (transform or clipping):
908 return shape
909 else:
910 group = Group()
911 if transform:
912 self.applyTransformOnGroup(transform, group)
913 if clipping:
914 group.add(clipping)
915 group.add(shape)
916 return group
917
918 def convert_length_attrs(self, node, *attrs, em_base=DEFAULT_FONT_SIZE, **kwargs):
919 # Support node both as NodeTracker or lxml node
920 getAttr = (
921 node.getAttribute if hasattr(node, 'getAttribute')
922 else lambda attr: node.attrib.get(attr, '')
923 )
924 convLength = self.attrConverter.convertLength
925 defaults = kwargs.get('defaults', (0.0,) * len(attrs))
926 return [
927 convLength(getAttr(attr), attr_name=attr, em_base=em_base, default=default)
928 for attr, default in zip(attrs, defaults)
929 ]
930
931 def convertLine(self, node):
932 points = self.convert_length_attrs(node, 'x1', 'y1', 'x2', 'y2')
933 nudge_points(points)
934 return Line(*points)
935
936 def convertRect(self, node):
937 x, y, width, height, rx, ry = self.convert_length_attrs(
938 node, 'x', 'y', 'width', 'height', 'rx', 'ry'
939 )
940 if rx > (width / 2):
941 rx = width / 2
942 if ry > (height / 2):
943 ry = height / 2
944 if rx and not ry:
945 ry = rx
946 elif ry and not rx:
947 rx = ry
948 return Rect(x, y, width, height, rx=rx, ry=ry)
949
950 def convertCircle(self, node):
951 # not rendered if r == 0, error if r < 0.
952 cx, cy, r = self.convert_length_attrs(node, 'cx', 'cy', 'r')
953 return Circle(cx, cy, r)
954
955 def convertEllipse(self, node):
956 cx, cy, rx, ry = self.convert_length_attrs(node, 'cx', 'cy', 'rx', 'ry')
957 width, height = rx, ry
958 return Ellipse(cx, cy, width, height)
959
960 def convertPolyline(self, node):
961 points = node.getAttribute("points")
962 points = points.replace(',', ' ')
963 points = points.split()
964 points = list(map(self.attrConverter.convertLength, points))
965 if len(points) % 2 != 0 or len(points) == 0:
966 # Odd number of coordinates or no coordinates, invalid polyline
967 return None
968
969 nudge_points(points)
970 polyline = PolyLine(points)
971 self.applyStyleOnShape(polyline, node)
972 has_fill = self.attrConverter.findAttr(node, 'fill') not in ('', 'none')
973
974 if has_fill:
975 # ReportLab doesn't fill polylines, so we are creating a polygon
976 # polygon copy of the polyline, but without stroke.
977 group = Group()
978 polygon = Polygon(points)
979 self.applyStyleOnShape(polygon, node)
980 polygon.strokeColor = None
981 group.add(polygon)
982 group.add(polyline)
983 return group
984
985 return polyline
986
987 def convertPolygon(self, node):
988 points = node.getAttribute("points")
989 points = points.replace(',', ' ')
990 points = points.split()
991 points = list(map(self.attrConverter.convertLength, points))
992 if len(points) % 2 != 0 or len(points) == 0:
993 # Odd number of coordinates or no coordinates, invalid polygon
994 return None
995 nudge_points(points)
996 shape = Polygon(points)
997
998 return shape
999
1000 def convertText(self, node):
1001 attrConv = self.attrConverter
1002 xml_space = node.getAttribute(f"{{{XML_NS}}}space")
1003 if xml_space:
1004 preserve_space = xml_space == 'preserve'
1005 else:
1006 preserve_space = self.preserve_space
1007
1008 gr = Group()
1009
1010 frag_lengths = []
1011
1012 dx0, dy0 = 0, 0
1013 x1, y1 = 0, 0
1014 ff = attrConv.findAttr(node, "font-family") or DEFAULT_FONT_NAME
1015 fw = attrConv.findAttr(node, "font-weight") or DEFAULT_FONT_WEIGHT
1016 fstyle = attrConv.findAttr(node, "font-style") or DEFAULT_FONT_STYLE
1017 ff = attrConv.convertFontFamily(ff, fw, fstyle)
1018 fs = attrConv.findAttr(node, "font-size") or str(DEFAULT_FONT_SIZE)
1019 fs = attrConv.convertLength(fs)
1020 x, y = self.convert_length_attrs(node, 'x', 'y', em_base=fs)
1021 for subnode, text, is_tail in iter_text_node(node, preserve_space):
1022 if not text:
1023 continue
1024 has_x, has_y = False, False
1025 dx, dy = 0, 0
1026 baseLineShift = 0
1027 if not is_tail:
1028 x1, y1, dx, dy = self.convert_length_attrs(subnode, 'x', 'y', 'dx', 'dy', em_base=fs)
1029 has_x, has_y = (subnode.attrib.get('x', '') != '', subnode.attrib.get('y', '') != '')
1030 dx0 = dx0 + (dx[0] if isinstance(dx, list) else dx)
1031 dy0 = dy0 + (dy[0] if isinstance(dy, list) else dy)
1032 baseLineShift = subnode.attrib.get("baseline-shift", '0')
1033 if baseLineShift in ("sub", "super", "baseline"):
1034 baseLineShift = {"sub": -fs/2, "super": fs/2, "baseline": 0}[baseLineShift]
1035 else:
1036 baseLineShift = attrConv.convertLength(baseLineShift, em_base=fs)
1037
1038 frag_lengths.append(stringWidth(text, ff, fs))
1039
1040 # When x, y, dx, or dy is a list, we calculate position for each char of text.
1041 if any(isinstance(val, list) for val in (x1, y1, dx, dy)):
1042 if has_x:
1043 xlist = x1 if isinstance(x1, list) else [x1]
1044 else:
1045 xlist = [x + dx0 + sum(frag_lengths[:-1])]
1046 if has_y:
1047 ylist = y1 if isinstance(y1, list) else [y1]
1048 else:
1049 ylist = [y + dy0]
1050 dxlist = dx if isinstance(dx, list) else [dx]
1051 dylist = dy if isinstance(dy, list) else [dy]
1052 last_x, last_y, last_char = xlist[0], ylist[0], ''
1053 for char_x, char_y, char_dx, char_dy, char in itertools.zip_longest(
1054 xlist, ylist, dxlist, dylist, text):
1055 if char is None:
1056 break
1057 if char_dx is None:
1058 char_dx = 0
1059 if char_dy is None:
1060 char_dy = 0
1061 new_x = char_dx + (
1062 last_x + stringWidth(last_char, ff, fs) if char_x is None else char_x
1063 )
1064 new_y = char_dy + (last_y if char_y is None else char_y)
1065 shape = String(new_x, -(new_y - baseLineShift), char)
1066 self.applyStyleOnShape(shape, node)
1067 if node_name(subnode) == 'tspan':
1068 self.applyStyleOnShape(shape, subnode)
1069 gr.add(shape)
1070 last_x = new_x
1071 last_y = new_y
1072 last_char = char
1073 else:
1074 new_x = (x1 + dx) if has_x else (x + dx0 + sum(frag_lengths[:-1]))
1075 new_y = (y1 + dy) if has_y else (y + dy0)
1076 shape = String(new_x, -(new_y - baseLineShift), text)
1077 self.applyStyleOnShape(shape, node)
1078 if node_name(subnode) == 'tspan':
1079 self.applyStyleOnShape(shape, subnode)
1080 gr.add(shape)
1081
1082 gr.scale(1, -1)
1083
1084 return gr
1085
1086 def convertPath(self, node):
1087 d = node.get('d')
1088 if not d:
1089 return None
1090 normPath = normalise_svg_path(d)
1091 path = Path()
1092 points = path.points
1093 # Track subpaths needing to be closed later
1094 unclosed_subpath_pointers = []
1095 subpath_start = []
1096 lastop = ''
1097 last_quadratic_cp = None
1098
1099 for i in range(0, len(normPath), 2):
1100 op, nums = normPath[i:i+2]
1101
1102 if op in ('m', 'M') and i > 0 and path.operators[-1] != _CLOSEPATH:
1103 unclosed_subpath_pointers.append(len(path.operators))
1104
1105 # moveto absolute
1106 if op == 'M':
1107 path.moveTo(*nums)
1108 subpath_start = points[-2:]
1109 # lineto absolute
1110 elif op == 'L':
1111 path.lineTo(*nums)
1112
1113 # moveto relative
1114 elif op == 'm':
1115 if len(points) >= 2:
1116 if lastop in ('Z', 'z'):
1117 starting_point = subpath_start
1118 else:
1119 starting_point = points[-2:]
1120 xn, yn = starting_point[0] + nums[0], starting_point[1] + nums[1]
1121 path.moveTo(xn, yn)
1122 else:
1123 path.moveTo(*nums)
1124 subpath_start = points[-2:]
1125 # lineto relative
1126 elif op == 'l':
1127 xn, yn = points[-2] + nums[0], points[-1] + nums[1]
1128 path.lineTo(xn, yn)
1129
1130 # horizontal/vertical line absolute
1131 elif op == 'H':
1132 path.lineTo(nums[0], points[-1])
1133 elif op == 'V':
1134 path.lineTo(points[-2], nums[0])
1135
1136 # horizontal/vertical line relative
1137 elif op == 'h':
1138 path.lineTo(points[-2] + nums[0], points[-1])
1139 elif op == 'v':
1140 path.lineTo(points[-2], points[-1] + nums[0])
1141
1142 # cubic bezier, absolute
1143 elif op == 'C':
1144 path.curveTo(*nums)
1145 elif op == 'S':
1146 x2, y2, xn, yn = nums
1147 if len(points) < 4 or lastop not in {'c', 'C', 's', 'S'}:
1148 xp, yp, x0, y0 = points[-2:] * 2
1149 else:
1150 xp, yp, x0, y0 = points[-4:]
1151 xi, yi = x0 + (x0 - xp), y0 + (y0 - yp)
1152 path.curveTo(xi, yi, x2, y2, xn, yn)
1153
1154 # cubic bezier, relative
1155 elif op == 'c':
1156 xp, yp = points[-2:]
1157 x1, y1, x2, y2, xn, yn = nums
1158 path.curveTo(xp + x1, yp + y1, xp + x2, yp + y2, xp + xn, yp + yn)
1159 elif op == 's':
1160 x2, y2, xn, yn = nums
1161 if len(points) < 4 or lastop not in {'c', 'C', 's', 'S'}:
1162 xp, yp, x0, y0 = points[-2:] * 2
1163 else:
1164 xp, yp, x0, y0 = points[-4:]
1165 xi, yi = x0 + (x0 - xp), y0 + (y0 - yp)
1166 path.curveTo(xi, yi, x0 + x2, y0 + y2, x0 + xn, y0 + yn)
1167
1168 # quadratic bezier, absolute
1169 elif op == 'Q':
1170 x0, y0 = points[-2:]
1171 x1, y1, xn, yn = nums
1172 last_quadratic_cp = (x1, y1)
1173 (x0, y0), (x1, y1), (x2, y2), (xn, yn) = \
1174 convert_quadratic_to_cubic_path((x0, y0), (x1, y1), (xn, yn))
1175 path.curveTo(x1, y1, x2, y2, xn, yn)
1176 elif op == 'T':
1177 if last_quadratic_cp is not None:
1178 xp, yp = last_quadratic_cp
1179 else:
1180 xp, yp = points[-2:]
1181 x0, y0 = points[-2:]
1182 xi, yi = x0 + (x0 - xp), y0 + (y0 - yp)
1183 last_quadratic_cp = (xi, yi)
1184 xn, yn = nums
1185 (x0, y0), (x1, y1), (x2, y2), (xn, yn) = \
1186 convert_quadratic_to_cubic_path((x0, y0), (xi, yi), (xn, yn))
1187 path.curveTo(x1, y1, x2, y2, xn, yn)
1188
1189 # quadratic bezier, relative
1190 elif op == 'q':
1191 x0, y0 = points[-2:]
1192 x1, y1, xn, yn = nums
1193 x1, y1, xn, yn = x0 + x1, y0 + y1, x0 + xn, y0 + yn
1194 last_quadratic_cp = (x1, y1)
1195 (x0, y0), (x1, y1), (x2, y2), (xn, yn) = \
1196 convert_quadratic_to_cubic_path((x0, y0), (x1, y1), (xn, yn))
1197 path.curveTo(x1, y1, x2, y2, xn, yn)
1198 elif op == 't':
1199 if last_quadratic_cp is not None:
1200 xp, yp = last_quadratic_cp
1201 else:
1202 xp, yp = points[-2:]
1203 x0, y0 = points[-2:]
1204 xn, yn = nums
1205 xn, yn = x0 + xn, y0 + yn
1206 xi, yi = x0 + (x0 - xp), y0 + (y0 - yp)
1207 last_quadratic_cp = (xi, yi)
1208 (x0, y0), (x1, y1), (x2, y2), (xn, yn) = \
1209 convert_quadratic_to_cubic_path((x0, y0), (xi, yi), (xn, yn))
1210 path.curveTo(x1, y1, x2, y2, xn, yn)
1211
1212 # elliptical arc
1213 elif op in ('A', 'a'):
1214 rx, ry, phi, fA, fS, x2, y2 = nums
1215 x1, y1 = points[-2:]
1216 if op == 'a':
1217 x2 += x1
1218 y2 += y1
1219 if abs(rx) <= 1e-10 or abs(ry) <= 1e-10:
1220 path.lineTo(x2, y2)
1221 else:
1222 bp = bezier_arc_from_end_points(x1, y1, rx, ry, phi, fA, fS, x2, y2)
1223 for _, _, x1, y1, x2, y2, xn, yn in bp:
1224 path.curveTo(x1, y1, x2, y2, xn, yn)
1225
1226 # close path
1227 elif op in ('Z', 'z'):
1228 path.closePath()
1229
1230 else:
1231 logger.debug("Suspicious path operator: %s", op)
1232
1233 if op not in ('Q', 'q', 'T', 't'):
1234 last_quadratic_cp = None
1235 lastop = op
1236
1237 gr = Group()
1238 self.applyStyleOnShape(path, node)
1239
1240 if path.operators[-1] != _CLOSEPATH:
1241 unclosed_subpath_pointers.append(len(path.operators))
1242
1243 if unclosed_subpath_pointers and path.fillColor is not None:
1244 # ReportLab doesn't fill unclosed paths, so we are creating a copy
1245 # of the path with all subpaths closed, but without stroke.
1246 # https://bitbucket.org/rptlab/reportlab/issues/99/
1247 closed_path = NoStrokePath(copy_from=path)
1248 for pointer in reversed(unclosed_subpath_pointers):
1249 closed_path.operators.insert(pointer, _CLOSEPATH)
1250 gr.add(closed_path)
1251 path.fillColor = None
1252
1253 gr.add(path)
1254 return gr
1255
1256 def convertImage(self, node):
1257 if not haveImages:
1258 logger.warning(
1259 "Unable to handle embedded images. Maybe the pillow library is missing?"
1260 )
1261 return None
1262
1263 x, y, width, height = self.convert_length_attrs(node, 'x', 'y', 'width', 'height')
1264 image = node._resolved_target
1265 image = Image(int(x), int(y + height), int(width), int(height), image)
1266
1267 group = Group(image)
1268 group.translate(0, (y + height) * 2)
1269 group.scale(1, -1)
1270 return group
1271
1272 def applyTransformOnGroup(self, transform, group):
1273 """Apply an SVG transformation to a RL Group shape.
1274
1275 The transformation is the value of an SVG transform attribute
1276 like transform="scale(1, -1) translate(10, 30)".
1277
1278 rotate(<angle> [<cx> <cy>]) is equivalent to:
1279 translate(<cx> <cy>) rotate(<angle>) translate(-<cx> -<cy>)
1280 """
1281
1282 tr = self.attrConverter.convertTransform(transform)
1283 for op, values in tr:
1284 if op == "scale":
1285 if not isinstance(values, tuple):
1286 values = (values, values)
1287 group.scale(*values)
1288 elif op == "translate":
1289 if isinstance(values, (int, float)):
1290 # From the SVG spec: If <ty> is not provided, it is assumed to be zero.
1291 values = values, 0
1292 group.translate(*values)
1293 elif op == "rotate":
1294 if not isinstance(values, tuple) or len(values) == 1:
1295 group.rotate(values)
1296 elif len(values) == 3:
1297 angle, cx, cy = values
1298 group.translate(cx, cy)
1299 group.rotate(angle)
1300 group.translate(-cx, -cy)
1301 elif op == "skewX":
1302 group.skew(values, 0)
1303 elif op == "skewY":
1304 group.skew(0, values)
1305 elif op == "matrix" and len(values) == 6:
1306 group.transform = mmult(group.transform, values)
1307 else:
1308 logger.debug("Ignoring transform: %s %s", op, values)
1309
1310 def applyStyleOnShape(self, shape, node, only_explicit=False):
1311 """
1312 Apply styles from an SVG element to an RLG shape.
1313 If only_explicit is True, only attributes really present are applied.
1314 """
1315
1316 # RLG-specific: all RLG shapes
1317 "Apply style attributes of a sequence of nodes to an RL shape."
1318
1319 # tuple format: (svgAttributes, rlgAttr, converter, default)
1320 mappingN = (
1321 (["fill"], "fillColor", "convertColor", ["black"]),
1322 (["fill-opacity"], "fillOpacity", "convertOpacity", [1]),
1323 (["fill-rule"], "_fillRule", "convertFillRule", ["nonzero"]),
1324 (["stroke"], "strokeColor", "convertColor", ["none"]),
1325 (["stroke-width"], "strokeWidth", "convertLength", ["1"]),
1326 (["stroke-opacity"], "strokeOpacity", "convertOpacity", [1]),
1327 (["stroke-linejoin"], "strokeLineJoin", "convertLineJoin", ["0"]),
1328 (["stroke-linecap"], "strokeLineCap", "convertLineCap", ["0"]),
1329 (["stroke-dasharray"], "strokeDashArray", "convertDashArray", ["none"]),
1330 )
1331 mappingF = (
1332 (
1333 ["font-family", "font-weight", "font-style"],
1334 "fontName", "convertFontFamily",
1335 [DEFAULT_FONT_NAME, DEFAULT_FONT_WEIGHT, DEFAULT_FONT_STYLE]
1336 ),
1337 (["font-size"], "fontSize", "convertLength", [str(DEFAULT_FONT_SIZE)]),
1338 (["text-anchor"], "textAnchor", "id", ["start"]),
1339 )
1340
1341 if shape.__class__ == Group:
1342 # Recursively apply style on Group subelements
1343 for subshape in shape.contents:
1344 self.applyStyleOnShape(subshape, node, only_explicit=only_explicit)
1345 return
1346
1347 ac = self.attrConverter
1348 for mapping in (mappingN, mappingF):
1349 if shape.__class__ != String and mapping == mappingF:
1350 continue
1351 for (svgAttrNames, rlgAttr, func, defaults) in mapping:
1352 svgAttrValues = []
1353 for index, svgAttrName in enumerate(svgAttrNames):
1354 svgAttrValue = ac.findAttr(node, svgAttrName)
1355 if svgAttrValue == '':
1356 if only_explicit:
1357 continue
1358 if (
1359 svgAttrName == 'fill-opacity'
1360 and getattr(shape, 'fillColor', None) is not None
1361 and getattr(shape.fillColor, 'alpha', 1) != 1
1362 ):
1363 svgAttrValue = shape.fillColor.alpha
1364 elif (
1365 svgAttrName == 'stroke-opacity'
1366 and getattr(shape, 'strokeColor', None) is not None
1367 and getattr(shape.strokeColor, 'alpha', 1) != 1
1368 ):
1369 svgAttrValue = shape.strokeColor.alpha
1370 else:
1371 svgAttrValue = defaults[index]
1372 if svgAttrValue == "currentColor":
1373 svgAttrValue = ac.findAttr(node.parent, "color") or defaults[index]
1374 if isinstance(svgAttrValue, str):
1375 svgAttrValue = svgAttrValue.replace('!important', '').strip()
1376 svgAttrValues.append(svgAttrValue)
1377 try:
1378 meth = getattr(ac, func)
1379 setattr(shape, rlgAttr, meth(*svgAttrValues))
1380 except (AttributeError, KeyError, ValueError):
1381 logger.debug("Exception during applyStyleOnShape")
1382 if getattr(shape, 'fillOpacity', None) is not None and shape.fillColor:
1383 shape.fillColor.alpha = shape.fillOpacity
1384 if getattr(shape, 'strokeWidth', None) == 0:
1385 # Quoting from the PDF 1.7 spec:
1386 # A line width of 0 denotes the thinnest line that can be rendered at device
1387 # resolution: 1 device pixel wide. However, some devices cannot reproduce 1-pixel
1388 # lines, and on high-resolution devices, they are nearly invisible. Since the
1389 # results of rendering such zero-width lines are device-dependent, their use
1390 # is not recommended.
1391 shape.strokeColor = None
1392
1393
1394 def svg2rlg(path, resolve_entities=False, **kwargs):
1395 """
1396 Convert an SVG file to an RLG Drawing object.
1397 `path` can be a file, a file-like, or a file path as str or pathlib.Path.
1398 """
1399
1400 if isinstance(path, pathlib.Path):
1401 path = str(path)
1402
1403 # unzip .svgz file into .svg
1404 unzipped = False
1405 if isinstance(path, str) and os.path.splitext(path)[1].lower() == ".svgz":
1406 with gzip.open(path, 'rb') as f_in, open(path[:-1], 'wb') as f_out:
1407 shutil.copyfileobj(f_in, f_out)
1408 path = path[:-1]
1409 unzipped = True
1410
1411 svg_root = load_svg_file(path, resolve_entities=resolve_entities)
1412 if svg_root is None:
1413 return
1414
1415 # convert to a RLG drawing
1416 svgRenderer = SvgRenderer(path, **kwargs)
1417 drawing = svgRenderer.render(svg_root)
1418
1419 # remove unzipped .svgz file (.svg)
1420 if unzipped:
1421 os.remove(path)
1422
1423 return drawing
1424
1425
1426 def nudge_points(points):
1427 """ Nudge first coordinate if all coordinate pairs are identical.
1428
1429 This works around reportlab's decision to hide shapes of size zero, even
1430 when the stroke should be visible.
1431 """
1432 if not points:
1433 return
1434 if len(points) < 4:
1435 return
1436 x = points[0]
1437 y = points[1]
1438 for i in range(2, len(points)-1, 2):
1439 if x != points[i] or y != points[i+1]:
1440 break
1441 else:
1442 # All points were identical, so we nudge.
1443 points[0] *= 1.0000001
1444
1445
1446 def load_svg_file(path, resolve_entities=False):
1447 parser = etree.XMLParser(
1448 remove_comments=True, recover=True, resolve_entities=resolve_entities
1449 )
1450 try:
1451 doc = etree.parse(path, parser=parser)
1452 svg_root = doc.getroot()
1453 except Exception as exc:
1454 logger.error("Failed to load input file! (%s)", exc)
1455 else:
1456 return svg_root
1457
1458
1459 def node_name(node):
1460 """Return lxml node name without the namespace prefix."""
1461
1462 try:
1463 return node.tag.split('}')[-1]
1464 except AttributeError:
1465 pass
1466
1467
1468 def iter_text_node(node, preserve_space, level=0):
1469 """
1470 Recursively iterate through text node and its children, including node tails.
1471 """
1472 level0 = level == 0
1473 text = clean_text(
1474 node.text, preserve_space, strip_start=level0, strip_end=(level0 and len(node.getchildren()) == 0)
1475 ) if node.text else None
1476
1477 yield node, text, False
1478
1479 for child in node.iter_children():
1480 yield from iter_text_node(child, preserve_space, level=level + 1)
1481
1482 if level > 0: # We are not interested by tail of main node.
1483 strip_end = level <= 1 and node.getnext() is None
1484 tail = clean_text(node.tail, preserve_space, strip_end=strip_end) if node.tail else None
1485 if tail not in (None, ''):
1486 yield node.parent, tail, True
1487
1488
1489 def clean_text(text, preserve_space, strip_start=False, strip_end=False):
1490 """Text cleaning as per https://www.w3.org/TR/SVG/text.html#WhiteSpace"""
1491 if text is None:
1492 return None
1493 text = text.replace('\r\n', ' ').replace('\n', ' ').replace('\t', ' ')
1494 if not preserve_space:
1495 if strip_start:
1496 text = text.lstrip()
1497 if strip_end:
1498 text = text.rstrip()
1499 while ' ' in text:
1500 text = text.replace(' ', ' ')
1501 return text
1502
1503
1504 def copy_shape_properties(source_shape, dest_shape):
1505 for prop, val in source_shape.getProperties().items():
1506 try:
1507 setattr(dest_shape, prop, val)
1508 except AttributeError:
1509 pass
1510
1511
1512 def monkeypatch_reportlab():
1513 """
1514 https://bitbucket.org/rptlab/reportlab/issues/95/
1515 ReportLab always use 'Even-Odd' filling mode for paths, this patch forces
1516 RL to honor the path fill rule mode (possibly 'Non-Zero Winding') instead.
1517 """
1518 from reportlab.pdfgen.canvas import Canvas
1519 from reportlab.graphics import shapes
1520
1521 original_renderPath = shapes._renderPath
1522
1523 def patchedRenderPath(path, drawFuncs, **kwargs):
1524 # Patched method to transfer fillRule from Path to PDFPathObject
1525 # Get back from bound method to instance
1526 try:
1527 drawFuncs[0].__self__.fillMode = path._fillRule
1528 except AttributeError:
1529 pass
1530 return original_renderPath(path, drawFuncs, **kwargs)
1531 shapes._renderPath = patchedRenderPath
1532
1533 original_drawPath = Canvas.drawPath
1534
1535 def patchedDrawPath(self, path, **kwargs):
1536 current = self._fillMode
1537 if hasattr(path, 'fillMode'):
1538 self._fillMode = path.fillMode
1539 else:
1540 self._fillMode = FILL_NON_ZERO
1541 original_drawPath(self, path, **kwargs)
1542 self._fillMode = current
1543 Canvas.drawPath = patchedDrawPath
1544
1545
1546 monkeypatch_reportlab()