SVG Elements Parsing
svgelements is a high-fidelity Python library for parsing and geometrically rendering SVG (Scalable Vector Graphics) files. It aims to correctly process SVG for use as geometric data, providing robust representations for core SVG elements such as Path, Matrix, Angle, Length, Color, and Point. The library is compatible with Python 3+ and adheres to SVG standard 1.1 and elements of 2.0, originating from the MeerK40t laser cutting project. It is currently at version 1.9.6 and sees active maintenance with frequent patch releases.
Warnings
- breaking The project was renamed from `svg.elements` to `svgelements`. Older code using `from svg.elements import ...` will no longer work and needs to be updated to `from svgelements import ...`.
- gotcha Calculating the length of `CubicBezier` and `Arc` path segments via `Path.length()` or similar methods can be computationally intensive and slow, as it relies on geometric approximation by default. Performance can be significantly improved by installing `scipy`.
- deprecated The `write_xml` and `string_xml` methods were introduced around version 1.9.0, standardizing how SVG objects are serialized. While not strictly a 'breaking' change for existing code that didn't use this functionality, the internal structure for writing XML was significantly re-factored. Relying on pre-1.9.0 implicit XML generation methods may lead to unexpected behavior or missing features.
- gotcha Loading embedded images within SVG files using `SVGImage` objects implicitly requires the `Pillow` (PIL fork) library. If `Pillow` is not installed, image loading within parsed SVGs will fail silently or raise errors related to missing image handling.
- gotcha The `SVG.parse()` method accepts `width`, `height`, and `ppi` parameters. These values are crucial for correctly interpreting relative SVG units (like percentages) and converting between different unit systems, as the SVG specification itself does not directly define a 'physical' view size or pixels per inch.
Install
-
pip install svgelements
Imports
- SVG
from svg.elements import SVG
from svgelements import SVG
- *
from svgelements import *
Quickstart
from svgelements import SVG, Rect, Group
import io
# Example 1: Parse an SVG string
svg_string = '''<svg width="100" height="100">
<rect x="10" y="10" width="80" height="80" fill="red" />
</svg>'''
svg_doc = SVG.parse(io.StringIO(svg_string))
print(f"Parsed SVG root element: {svg_doc.xml_tag}")
for element in svg_doc.elements():
if isinstance(element, Rect):
print(f" Found Rect: x={element.x}, y={element.y}, width={element.width}, height={element.height}, fill={element.fill}")
# Example 2: Create an SVG programmatically and write to a file
new_svg = SVG()
new_svg.append(Rect(x=0, y=0, width="2in", height="2in", fill="blue", stroke="black"))
new_svg.append(Group(id="my_group").add(Rect(x=10, y=10, width=30, height=30, fill="green")))
# Save to a temporary file
output_filename = "output.svg"
new_svg.write_xml(output_filename)
print(f"Generated SVG saved to {output_filename}")
# You can also get the XML as a string
svg_output_string = new_svg.string_xml()
print("\nGenerated SVG string:\n" + svg_output_string)
# Clean up the created file
import os
if os.path.exists(output_filename):
os.remove(output_filename)
print(f"Cleaned up {output_filename}")