inkext.svg¶
A simple library for SVG output.
- class inkext.svg.SVGContext(document: _ElementTree)¶
SVG document context.
- add_elem(node: _Element, parent: _Element | None = None) None ¶
Add the element to the parent.
Uses the :current_parent: if parent is None.
- create_arc(arc: Arc, style: str | None = None, parent: _Element | None = None, attrs: dict[str, str] | None = None) _Element ¶
Create an SVG circular arc.
- create_circle(center: Sequence[float], radius: float, style: str | None = None, parent: _Element | None = None) _Element ¶
Create an SVG circle element.
- create_circular_arc(startp: Sequence[float], endp: Sequence[float], radius: float, sweep_flag: int, style: str | None = None, parent: _Element | None = None, attrs: dict[str, str] | None = None) _Element ¶
Create an SVG circular arc.
- create_clip_path(path: _Element) _Element | None ¶
Create an SVG clipPath.
- create_curve(control_points: Sequence[TPoint], style: str | None = None, parent: TElement | None = None, attrs: dict[str, str] | None = None) TElement ¶
Create an SVG cubic bezier curve.
- Parameters:
control_points – Tuple of four control points of a cubic bezier curve.
style – A CSS style string.
parent – The parent element (or Inkscape layer).
attrs – Dictionary of SVG element attributes.
- Returns:
An SVG path Element node.
- classmethod create_document(width: float, height: float, doc_id: str | None = None, doc_units: str = 'px') Self ¶
Create a minimal SVG document.
- Returns:
An SVGContext
- create_ellipse(center: Sequence[float], rx: float, ry: float, phi: float = 0, start_angle: float = 0, sweep_angle: float = 0, style: str | None = None, parent: _Element | None = None) _Element ¶
Create an SVG ellipse using center parameterization.
- create_group(children: _Element | None = None, style: str | None = None, parent: _Element | None = None) _Element ¶
Create an SVG group.
- create_line(p1: Sequence[float], p2: Sequence[float], style: str | None = None, parent: _Element | None = None, attrs: dict[str, str] | None = None) _Element ¶
Create an SVG path consisting of one line segment.
- create_polygon(vertices: Sequence[TPoint], close_polygon: bool = True, close_path: bool = False, style: str | None = None, parent: TElement | None = None, attrs: dict[str, str] | None = None) TElement | None ¶
Create an SVG path describing a polygon.
- Parameters:
vertices – A sequence 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_polygons(polygons: Iterable[Sequence[TPoint]], close_polygon: bool = True, close_path: bool = False, style: str | None = None, parent: TElement | None = None, attrs: dict[str, str] | None = None) TElement | None ¶
Create an SVG path describing a polygon.
- Parameters:
polygons – A collection of polygons,
vertices. (each a sequence of 2D polygon) – 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: Sequence[geom2d.Line | geom2d.Arc | geom2d.CubicBezier | Sequence[TPoint]], close_path: bool = False, style: str | None = None, parent: TElement | None = None, attrs: dict[str, str] | None = None) TElement | None ¶
Create an SVG path from a sequence of curve segments.
- Parameters:
path – A 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.
- create_rect(position: Sequence[float], width: float, height: float, style: str | None = None, parent: _Element | None = None) _Element ¶
Create an SVG rect element.
- create_simple_marker(marker_id: str, d: str, style: str, transform: str, replace: bool = False) _Element ¶
Create an SVG line end marker glyph.
The glyph Element is placed under the document root.
- create_text(text: str, x: float, y: float, line_height: float | None = None, text_anchor: str | None = None, style: str | None = None, parent: _Element | None = None) _Element ¶
Create a text block.
- generate_id(prefix: str = '_id') str ¶
Create a unique XML id attribute value.
- Parameters:
prefix – The prefix prepended to a random number. Default prefix is ‘_id’.
- Returns:
A random id string that has a fairly low chance of collision with previously generated ids.
- get_document_size() tuple[float, float] ¶
Return width and height of document in user units as a tuple (W, H).
- get_element_transform(node: TElement, root: TElement | None = None) TMatrix | None ¶
Get the combined transform of the element and its parents.
- Parameters:
node – The element node.
root – The root element to stop searching, or document root if None.
- Returns:
The combined transform matrix or None.
- get_node_by_id(node_id: str) _Element | None ¶
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_parent_transform(node: TElement, root: TElement | None = None) TMatrix | None ¶
Get the combined transform of the node’s parents.
- Parameters:
node – The child node.
root – The root element to stop searching, or document root if None.
- Returns:
The parent transform matrix or the identity matrix if none found.
- node_is_group(node: _Element) bool ¶
Return True if the node is an SVG group.
- classmethod parse(stream: TextIO | None = None, huge_tree: bool = True) Self ¶
Parse an SVG file (or stdin) and return an SVGContext.
- Parameters:
stream – The input stream to parse. If this is None stdin will be read by default.
huge_tree – Disable security restrictions and support very deep trees.
- Returns:
An SVGContext
- remove_node(node: _Element) None ¶
Remove node from parent.
- scale_inline_style(inline_style: str) str ¶
Rescale inline style quantities to user units.
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.
- set_clip_path(node: _Element, clip_path: _Element) None ¶
Set the clipping path to the specified node.
- set_default_parent(parent: _Element) None ¶
Set the current default parent (or layer).
- set_precision(precision: int | None = None) None ¶
Set the output precision.
- Parameters:
precision – The number of digits after the decimal point.
- styles_from_templates(style_templates: dict, default_map: dict, template_map: dict | None = None) dict[str, str] ¶
Create a map of named CSS styles from a template.
Populates 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.
- unit2uu(value: str | float, from_unit: str | None = None) float ¶
Convert value to user (document) units.
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 assuming they have the same aspect ratio.
SVG/Inkscape units and SVG viewBoxes can be 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 float value or a numeric string value with an optional unit identifier suffix (ie ‘3mm’, ‘10pt, ‘5in’), or a float value. If the value is a float or the string does not have a unit suffix then from_unit will be used.
from_unit – Optional string specifying the source units for the conversion. Default is doc units.
to_unit – Optional string specifying the destination units for the conversion. Default is doc units.
- Returns:
A float value or 0.0 if the string can’t be parsed.
- unit_convert(scalar: str | float | None, from_unit: str | None = None, to_unit: str | None = None) float ¶
Perform unit conversion on a scalar value.
Convert a scalar value from a source unit (ie 2.3, ‘3’, ‘3mm’, ‘5in’, etc) to a float value in a destination unit (user/document units by default).
- Parameters:
scalar – A string scalar with an optional unit identifier suffix. (ie ‘3mm’, ‘4.5’, ‘10pt, ‘5.3in’)
from_unit – Optional default source unit. Default is document (user) units.
to_unit – An SVG unit id of the destination unit conversion. Default is document (user) units.
- Returns:
A float value or 0.0 if the string can’t be parsed.
- write_document(stream: TextIO, pretty_print: bool = False) None ¶
Write the SVG document to a stream output.
- exception inkext.svg.SVGError¶
SVG etree error.
- inkext.svg.add_ns(tag: str, ns_map: dict[str, str], ns: str) str ¶
Prepend a mapped namespace to tag.
- inkext.svg.add_transform(node: TElement, matrix: TMatrix) None ¶
Add a transfrom to the node.
- inkext.svg.create_matrix_transform(matrix: TMatrix) str ¶
Create a SVG transform attribute value from matrix.
- inkext.svg.create_svg_document(width: str | float, height: str | float, doc_units: str = 'px', doc_id: str | None = None, nsmap: dict | None = None) _ElementTree ¶
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.
nsmap – Namespace mapping.
- Returns:
A node of type
lxml.etree.ElementTree
- inkext.svg.explode_path(path_data: str) list ¶
Break the path at node points into component segments.
- Parameters:
path_data – The
d
attribute value of a SVG path element.- Returns:
A list of path
d
attribute values.
- inkext.svg.geompath_to_svgpath(path: Iterable[geom2d.Line | geom2d.Arc | geom2d.EllipticalArc | geom2d.CubicBezier], scale: float = 1, close_path: bool = False) str ¶
Create an SVG path from a sequence of geometry segments.
- Parameters:
path – A sequence of Line, Arc, EllipticalArc, or CubicBezier segments.
scale – SVG scaling factor. Default is 1.
close_path – Close and join the the path ends by appending ‘Z’ to the end of the path (‘d’) attribute. Default is False.
- Returns:
An SVG path attribute value (the ‘d’ part).
- inkext.svg.get_node_by_id(root: _Element | _ElementTree, node_id: str) _Element | None ¶
Find an element in the specified element tree by id attribute.
- Parameters:
root – The root element to search.
node_id – The element id attribute value.
- Returns:
An element if found otherwise None.
- inkext.svg.get_node_by_tag(root: _Element, tag: str) _Element | None ¶
Find first element having specified tag name.
- inkext.svg.get_shape_elements(root: TElement | Iterable[TElement], visible_only: bool = True) Iterator[TElement] ¶
Get all visible shape elements descended from one or more root elements.
Basically just flattens the element tree by recursively descending the document/layer tree.
- inkext.svg.get_transform_matrix(node: TElement) TMatrix | None ¶
Get the transform matrix for an SVG node.
- inkext.svg.node_is_visible(node: _Element, check_parent: bool = True, _recurs: bool = False) bool ¶
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.
- inkext.svg.parse_path(path_data: str) Iterator[tuple] ¶
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_data – The ‘d’ attribute value of a SVG path element.
- Yields:
A path component 2-tuple of the form (cmd, params).
- inkext.svg.parse_transform_attr(stransform: str | None) TMatrix | None ¶
Parse an SVG transform attribute.
- Parameters:
stransform – A string containing the SVG transform list.
- Returns:
A single affine transform matrix or None.
- inkext.svg.path_tokenizer(path_data: str) Iterator[tuple[str, bool]] ¶
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.
- Parameters:
path_data – The
d
attribute of an SVG path.- Yields:
A 2-tuple with token and token type hint.
- inkext.svg.random_id(prefix: str = '_svg', rootnode: _Element | None = None) str ¶
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.
- inkext.svg.reverse_path(path_data: str) str ¶
Reverse nodes in a path. :param path_data: The
d
attribute value of a SVG path element.- Returns:
The
d
attribute value, with nodes reversed.
- inkext.svg.scalar_unit(scalar: str | None, default: str = 'px') str ¶
Get the unit part of an SVG/CSS scalar size value.
For example: ‘in’ from ‘15.3in’, or ‘px’ from ‘101px’.
- inkext.svg.scalar_value(scalar: str | None) float ¶
Get the numeric part of an SVG/CSS scalar size value.
For example: 15.3 from ‘15.3in’
- inkext.svg.set_transform(node: TElement, matrix: TMatrix) None ¶
Assign a transform matrix to the node.
This replaces any existing transforms.
- inkext.svg.stringify_parsed_path(parsed_path: Iterable[tuple]) str ¶
Convert a parsed path to a string.
This creates the
d
attribute value for a path element given a list of path commands and parameters as returned byparse_path()
.
- inkext.svg.strip_ns(tag: str) str ¶
Strip the namespace part from the tag if any.
- inkext.svg.svg_ns(tag: str) str ¶
Shortcut to prepend SVG namespace to tag.
- inkext.svg.unit_convert(value: str | float | None, from_unit: str = 'px', to_unit: str = 'px') float ¶
Convert a scalar value from one unit to another.
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’), or a float value.
from_unit – Optional default source unit identifier. Used if the input value is a float or if the unit identifier could not be parsed from the string value.
to_unit – Optional destination unit identifier of the unit conversion. Default is ‘px’.
- Returns:
A float value or 0.0 if the string can’t be parsed.
- inkext.svg.xlink_ns(tag: str) str ¶
Shortcut to prepend xlink namespace to tag.
- inkext.svg.xml_ns(tag: str) str ¶
Shortcut to prepend XML namespace to tag.