svg - SVG drawing/utility package¶
svg.svg¶
A simple library for SVG output.
-
class
svg.svg.SVGContext(document, font_size=None, x_height=None)[source]¶ SVG document context.
New SVG context.
Parameters: - document – An SVG ElementTree. The svg ‘width’ and ‘height’ attributes MUST be specified.
- font_height – CSS font-height in user units.
- ex_height – CSS x-height in user units.
-
classmethod
create_document(width, height, doc_id=None, doc_units=None)[source]¶ Create a minimal SVG document.
Returns: An ElementTree
-
classmethod
parse(filename=None, huge_tree=True)[source]¶ Parse an SVG file (or stdin) and return an SVGContext.
Parameters: filename – The SVG file to parse. If this is None stdin will be read by default. Returns: An SVGContext
-
unit2uu(value, from_unit=u'px')[source]¶ Convert a string/float that specifies a value in some source unit (ie ‘3mm’ or ‘5in’) to a float value in user units. The result will be scaled using the viewBox/viewport ratio. See http://www.w3.org/TR/SVG/coords.html#ViewBoxAttribute
Parameters: - value – A numeric string value with an optional unit identifier suffix (ie ‘3mm’, ‘10pt, ‘5in’), or a float value. If the string does not have a unit suffix then src_unit will be used.
- from_unit – A string specifying the units for the conversion. Default is ‘px’.
Returns: A float value or 0.0 if the string can’t be parsed.
-
uu2unit(value, to_unit=u'px')[source]¶ Convert a value in user units to a destination unit.
Parameters: - value – A float value in user units.
- to_unit – Destination unit (i.e. ‘in’, ‘mm’, etc.) Default is ‘px’.
Returns: The converted value.
-
unit_convert(value, to_unit=u'px', from_unit=u'px')[source]¶ Convert a string that specifies a scalar value in some source unit (ie ‘3mm’ or ‘5in’) to a float value in a destination unit (‘px’, or user units, by default). SVG/Inkscape units and viewBoxes are confusing… See http://www.w3.org/TR/SVG/coords.html#ViewBoxAttribute and http://www.w3.org/TR/SVG/coords.html#Units and http://wiki.inkscape.org/wiki/index.php/Units_In_Inkscape
Parameters: - value – A string scalar with an optional unit identifier suffix. (ie ‘3mm’, ‘10pt, ‘5.3in’)
- to_unit – An SVG unit id of the destination unit conversion. Default is ‘px’ (user units)
- from_unit – Optional default source unit. (‘px’ if unspecified)
Returns: A float value or 0.0 if the string can’t be parsed.
-
set_precision(precision)[source]¶ Set the output precision.
Parameters: precision – The number of digits after the decimal point.
-
float_eq(a, b)[source]¶ Compare two floats for equality in the SVG context. The two float are considered equal if the difference between them is less than epsilon. This is based on the current SVG numeric precision.
- For a discussion of floating point comparisons see:
- http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/
-
get_node_by_id(node_id)[source]¶ Find a node in the current document by id attribute.
Parameters: node_id – The node id attribute value. Returns: A node if found otherwise None.
-
get_element_transform(node, root=None)[source]¶ Get the combined transform of the element and it’s combined parent transforms.
Parameters: - node – The element node.
- root – The document root or where to stop searching.
Returns: The combined transform matrix or the identity matrix if none found.
-
get_parent_transform(node, root=None)[source]¶ Get the combined transform of the node’s parents.
Parameters: - node – The child node.
- root – The document root or where to stop searching.
Returns: The parent transform matrix or the identity matrix if none found.
-
node_is_visible(node, check_parent=True, _recurs=False)[source]¶ Return True if the node is visible. CSS visibility trumps SVG visibility attribute.
The node is not considered visible if the visibility style is hidden or collapse or if the display style is none. If the visibility style is inherit or check_parent is True then the visibility is determined by the parent node.
Parameters: - node – An etree.Element node
- check_parent – Recursively check parent nodes for visibility
Returns: True if the node is visible otherwise False.
-
parse_transform_attr(transform_attr)[source]¶ Parse an SVG transform attribute.
Parameters: transform_attr – A string containing the SVG transform list. Returns: A single affine transform matrix.
-
scale_inline_style(inline_style)[source]¶ For any inline style attribute name that ends with ‘width’, ‘height’, or ‘size’ scale the numeric value with an optional unit id suffix by converting it to user units with no unit id.
-
styles_from_templates(style_templates, default_map, template_map=None)[source]¶ Populate a dictionary of styles given a dictionary of templates and mappings. If a template key string ends with ‘width’, ‘height’, or ‘size’ it is assumed that the value is a numeric value with an optional unit id suffix and it will be automatically converted to user units with no unit id.
Parameters: - style_templates – A dictionary of style names to inline style template strings.
- default_map – A dictionary of template keys to default values. This must contain all template identifiers.
- template_map – A dictionary of template keys to values that override the defaults. Default is None.
Returns: A dictionary of inline styles.
-
create_line(p1, p2, style=None, parent=None, attrs=None)[source]¶ Create an SVG path consisting of one line segment.
-
create_circular_arc(startp, endp, radius, sweep_flag, style=None, parent=None, attrs=None)[source]¶ Create an SVG circular arc.
-
create_curve(startp, cp1=None, cp2=None, p2=None, style=None, parent=None, attrs=None)[source]¶ Create an SVG cubic bezier curve.
Parameters: - startp – The start point of the curve or an indexable collection of four control points.
- style – A CSS style string.
- parent – The parent element (or Inkscape layer).
- attrs – Dictionary of SVG element attributes.
Returns: An SVG path Element node.
-
create_polygon(vertices, close_polygon=True, close_path=False, style=None, parent=None, attrs=None)[source]¶ Create an SVG path describing a polygon.
Parameters: - vertices – An iterable collection of 2D polygon vertices. A vertice being a tuple containing x,y coordicates.
- close_polygon – Close the polygon if it isn’t already. Default is True.
- close_path – Close and join the the path ends by appending ‘Z’ to the end of the path (‘d’) attribute. Default is False.
- style – A CSS style string.
- parent – The parent element (or Inkscape layer).
- attrs – Dictionary of SVG element attributes.
Returns: An SVG path Element node, or None if the list of vertices is empty.
-
create_polypath(path, close_path=False, style=None, parent=None, attrs=None)[source]¶ Create an SVG path from a sequence of line and arc segments.
Parameters: - path – An iterable sequence of line, circular arc, or cubic Bezier curve segments. A line segment is a 2-tuple containing the endpoints. An arc segment is a 5-tuple containing the start point, end point, radius, angle, and center, respectively. The arc center is ignored. A cubic bezier segment is a 4-tuple containing the first endpoint, the first control point, the second control point, and the second endpoint.
- close_path – Close and join the the path ends by appending ‘Z’ to the end of the path (‘d’) attribute. Default is False.
- style – A CSS style string.
- parent – The parent element (i.e. Inkscape layer).
- attrs – Dictionary of SVG element attributes.
Returns: An SVG path Element node, or None if the path is empty.
-
svg.svg.path_tokenizer(path_data)[source]¶ Tokenize SVG path data.
A generator that yields tokens from path data. This will yield a tuple containing a command token or a numeric parameter token followed by a boolean flag that is True if the token is a command and False if the token is a numeric parameter.
Yields: A 2-tuple with token and token type hint.
-
svg.svg.parse_path(path_data)[source]¶ Parse an SVG path definition string. Converts relative values to absolute and shorthand commands to canonical (ie. H to L, S to C, etc.) Terminating Z (or z) converts to L.
If path syntax errors are encountered, parsing will simply stop. No exceptions are raised. This is by design so that parsing is relatively forgiving of input.
Implemented as a generator so that memory usage can be minimized for very long paths.
Parameters: path_def – The ‘d’ attribute value of a SVG path element. Yields: A path component 2-tuple of the form (cmd, params).
-
svg.svg.explode_path(path_data)[source]¶ Break the path at node points into component segments.
Parameters: path_def – The ‘d’ attribute value of a SVG path element. Returns: A list of path ‘d’ attribute values.
-
svg.svg.create_svg_document(width, height, doc_units=u'px', doc_id=None)[source]¶ Create a minimal SVG document tree.
The svg element viewbox attribute will maintain the size and attribute ratio as specified by width and height.
Parameters: - width – The width of the document in user units.
- height – The height of the document in user units.
- doc_units – The user unit type (i.e. ‘in’, ‘mm’, ‘pt’, ‘em’, etc.) By default this will be ‘px’.
- doc_id – The id attribute of the enclosing svg element. If None (default) then a random id will be generated.
Returns: An lxml.etree.ElementTree
-
svg.svg.random_id(prefix=u'_svg', rootnode=None)[source]¶ Create a random XML id attribute value.
Parameters: - prefix – The prefix prepended to a random number. Default is ‘_svg’.
- rootnode – The root element to search for id name collisions. Default is None in which case no search will be performed.
Returns: A random id string that has a fairly low chance of collision with previously generated ids.
svg.css¶
A simple library of functions to parse and format CSS style properties.
-
svg.css.CSS_COLORS= {u'indigo': (75, 0, 130), u'gold': (255, 215, 0), u'hotpink': (255, 105, 180), u'firebrick': (178, 34, 34), u'indianred': (205, 92, 92), u'yellow': (255, 255, 0), u'mistyrose': (255, 228, 225), u'darkolivegreen': (85, 107, 47), u'olive': (128, 128, 0), u'darkseagreen': (143, 188, 143), u'pink': (255, 192, 203), u'tomato': (255, 99, 71), u'lightcoral': (240, 128, 128), u'orangered': (255, 69, 0), u'navajowhite': (255, 222, 173), u'lime': (0, 255, 0), u'palegreen': (152, 251, 152), u'darkslategrey': (47, 79, 79), u'greenyellow': (173, 255, 47), u'burlywood': (222, 184, 135), u'seashell': (255, 245, 238), u'mediumspringgreen': (0, 250, 154), u'fuchsia': (255, 0, 255), u'papayawhip': (255, 239, 213), u'blanchedalmond': (255, 235, 205), u'chartreuse': (127, 255, 0), u'dimgray': (105, 105, 105), u'black': (0, 0, 0), u'peachpuff': (255, 218, 185), u'springgreen': (0, 255, 127), u'aquamarine': (127, 255, 212), u'white': (255, 255, 255), u'orange': (255, 165, 0), u'lightsalmon': (255, 160, 122), u'darkslategray': (47, 79, 79), u'brown': (165, 42, 42), u'ivory': (255, 255, 240), u'dodgerblue': (30, 144, 255), u'peru': (205, 133, 63), u'lawngreen': (124, 252, 0), u'chocolate': (210, 105, 30), u'crimson': (220, 20, 60), u'forestgreen': (34, 139, 34), u'darkgrey': (169, 169, 169), u'lightseagreen': (32, 178, 170), u'cyan': (0, 255, 255), u'mintcream': (245, 255, 250), u'silver': (192, 192, 192), u'antiquewhite': (250, 235, 215), u'mediumorchid': (186, 85, 211), u'skyblue': (135, 206, 235), u'gray': (128, 128, 128), u'darkturquoise': (0, 206, 209), u'goldenrod': (218, 165, 32), u'darkgreen': (0, 100, 0), u'floralwhite': (255, 250, 240), u'darkviolet': (148, 0, 211), u'darkgray': (169, 169, 169), u'moccasin': (255, 228, 181), u'saddlebrown': (139, 69, 19), u'grey': (128, 128, 128), u'darkslateblue': (72, 61, 139), u'lightskyblue': (135, 206, 250), u'lightpink': (255, 182, 193), u'mediumvioletred': (199, 21, 133), u'slategrey': (112, 128, 144), u'red': (255, 0, 0), u'deeppink': (255, 20, 147), u'limegreen': (50, 205, 50), u'darkmagenta': (139, 0, 139), u'palegoldenrod': (238, 232, 170), u'plum': (221, 160, 221), u'turquoise': (64, 224, 208), u'lightgrey': (211, 211, 211), u'lightgoldenrodyellow': (250, 250, 210), u'darkgoldenrod': (184, 134, 11), u'lavender': (230, 230, 250), u'maroon': (128, 0, 0), u'yellowgreen': (154, 205, 50), u'sandybrown': (244, 164, 96), u'thistle': (216, 191, 216), u'violet': (238, 130, 238), u'navy': (0, 0, 128), u'magenta': (255, 0, 255), u'dimgrey': (105, 105, 105), u'tan': (210, 180, 140), u'rosybrown': (188, 143, 143), u'olivedrab': (107, 142, 35), u'blue': (0, 0, 255), u'lightblue': (173, 216, 230), u'ghostwhite': (248, 248, 255), u'honeydew': (240, 255, 240), u'cornflowerblue': (100, 149, 237), u'slateblue': (106, 90, 205), u'linen': (250, 240, 230), u'darkblue': (0, 0, 139), u'powderblue': (176, 224, 230), u'seagreen': (46, 139, 87), u'darkkhaki': (189, 183, 107), u'snow': (255, 250, 250), u'sienna': (160, 82, 45), u'mediumblue': (0, 0, 205), u'royalblue': (65, 105, 225), u'lightcyan': (224, 255, 255), u'green': (0, 128, 0), u'mediumpurple': (147, 112, 219), u'midnightblue': (25, 25, 112), u'cornsilk': (255, 248, 220), u'paleturquoise': (175, 238, 238), u'bisque': (255, 228, 196), u'slategray': (112, 128, 144), u'darkcyan': (0, 139, 139), u'khaki': (240, 230, 140), u'wheat': (245, 222, 179), u'teal': (0, 128, 128), u'darkorchid': (153, 50, 204), u'deepskyblue': (0, 191, 255), u'salmon': (250, 128, 114), u'darkred': (139, 0, 0), u'steelblue': (70, 130, 180), u'palevioletred': (219, 112, 147), u'lightslategray': (119, 136, 153), u'aliceblue': (240, 248, 255), u'lightslategrey': (119, 136, 153), u'lightgreen': (144, 238, 144), u'orchid': (218, 112, 214), u'gainsboro': (220, 220, 220), u'mediumseagreen': (60, 179, 113), u'lightgray': (211, 211, 211), u'mediumturquoise': (72, 209, 204), u'lemonchiffon': (255, 250, 205), u'cadetblue': (95, 158, 160), u'lightyellow': (255, 255, 224), u'lavenderblush': (255, 240, 245), u'coral': (255, 127, 80), u'purple': (128, 0, 128), u'aqua': (0, 255, 255), u'whitesmoke': (245, 245, 245), u'mediumslateblue': (123, 104, 238), u'darkorange': (255, 140, 0), u'mediumaquamarine': (102, 205, 170), u'darksalmon': (233, 150, 122), u'beige': (245, 245, 220), u'blueviolet': (138, 43, 226), u'azure': (240, 255, 255), u'lightsteelblue': (176, 196, 222), u'oldlace': (253, 245, 230)}¶ CSS color names to hex rgb values.
-
svg.css.inline_style_to_dict(inline_style)[source]¶ Create a dictionary of style properties from an inline style attribute.
Parameters: inline_style – A string containing the value of a CSS style attribute. Returns: A dictionary of style properties.
-
svg.css.dict_to_inline_style(style_map)[source]¶ Create an inline style attribute string from a dictionary of CSS style properties.
Parameters: style_map – A dictionary of CSS style properties. Returns: A string containing inline CSS style properties.
-
svg.css.csscolor_to_rgb(css_color)[source]¶ Parse a CSS color property value into an RGB value.
Parameters: css_color – A CSS color property string. I.e. “#ffc0ee” or “white”. Returns: (r, g, b). Return type: A tuple containing the RGB values
-
svg.css.csshex_to_rgb(hex_color)[source]¶ Convert a CSS hex color property to RGB.
Parameters: hex_color – A CSS hex property string. Returns: (r, g, b). Returns (0, 0, 0) by default if the hex value can’t be parsed. Return type: The RGB value as a tuple of three integers
-
svg.css.cssrgb_to_rgb(rgb_color)[source]¶ Convert a CSS rgb or rgba color property to RGB.
Parameters: rgb_color – A CSS rgb property string: i.e. rgb(r, g, b). Returns: The RGB value as a tuple or list of three integers plus an optional fourth float value if there is an alpha channel. Returns (0, 0, 0) by default if the hex value can’t be parsed.
-
svg.css.parse_channel_value(value)[source]¶ Parse a CSS color channel value.
Parameters: value – A valid CSS color channel value string. Can be an integer number or an integer percentage. Returns: An integer value between 0 and 255. Default is 0 if the value isn’t a valid channel value.
-
svg.css.csscolor_to_cssrgb(color)[source]¶ Returns a CSS color in the form #rrggbb. If color is a numeric value then it is converted to a grayscale number. If the number is a floating point value between zero and one then it is scaled up to 0-255 grayscale. If the CSS color can’t be parsed then #000000 is returned.
Parameters: possibly malformed CSS color string or number. (A) – Returns: A CSS color in the form #rrggbb.
svg.geomsvg¶
Methods for converting SVG shape elements to geometry objects.
-
svg.geomsvg.svg_to_geometry(svg_elements, parent_transform=None)[source]¶ Convert the SVG shape elements to Line, Arc, and/or CubicBezier segments, and apply node/parent transforms. The coordinates of the segments will be absolute with respect to the parent container.
Parameters: - svg_elements – An iterable collection of 2-tuples consisting of SVG Element node and transform matrix.
- parent_transform – An optional parent transform to apply to all nodes. Default is None.
Returns: A list of paths, where a path is a list of one or more segments made of Line, Arc, or CubicBezier objects.
-
svg.geomsvg.svg_element_to_geometry(element, element_transform=None, parent_transform=None)[source]¶ Convert the SVG shape element to a list of one or more Line, Arc, and/or CubicBezier segments, and apply node/parent transforms. The coordinates of the segments will be absolute with respect to the parent container.
Parameters: - element – An SVG Element shape node.
- element_transform – An optional transform to apply to the element. Default is None.
- parent_transform – An optional parent transform to apply to the element. Default is None.
Returns: A list of zero or more paths. A path being a list of zero or more Line, Arc, EllipticalArc, or CubicBezier objects.
-
svg.geomsvg.parse_path_geom(path_data, ellipse_to_bezier=False)[source]¶ Parse SVG path data and convert to geometry objects.
Parameters: - path_data – The d attribute value of an SVG path element.
- ellipse_to_bezier – Convert elliptical arcs to bezier curves if True. Default is False.
Returns: A list of zero or more subpaths. A subpath being a list of zero or more Line, Arc, EllipticalArc, or CubicBezier objects.
-
svg.geomsvg.convert_rect(element)[source]¶ Convert an SVG rect shape element to four geom.Line segments.
Parameters: element – An SVG ‘rect’ element of the form <rect x=’X’ y=’Y’ width=’W’ height=’H’/> Returns: A clockwise wound polygon as a list of geom.Line segments.
-
svg.geomsvg.convert_line(element)[source]¶ Convert an SVG line shape element to a geom.Line.
Parameters: element – An SVG ‘line’ element of the form: <line x1=’X1’ y1=’Y1’ x2=’X2’ y2=’Y2/> Returns: geom.Line((x1, y1), (x2, y2)) Return type: A line segment
-
svg.geomsvg.convert_circle(element)[source]¶ Convert an SVG circle shape element to four circular arc segments.
Parameters: element – An SVG ‘circle’ element of the form: <circle r=’RX’ cx=’X’ cy=’Y’/> Returns: A counter-clockwise wound list of four circular geom.Arc segments.
-
svg.geomsvg.convert_ellipse(element)[source]¶ Convert an SVG ellipse shape element to a geom.Ellipse.
Parameters: element – An SVG ‘ellipse’ element of the form: <ellipse rx=’RX’ ry=’RY’ cx=’X’ cy=’Y’/> Returns: A geom.Ellipse.