Registry / serialization / svgelements

svgelements

JSON →
library1.9.6pypypi✓ verified 89d ago

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.

pip install svgelements
INSTALL
IMPORT
SIG · SVGELEMENTS
S
svgelements
serializationpythonv1.9.6
Install
1.6s avg
Import
72ms
Disk
17MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.9–3.13
musl
3.9–3.13
Install & Compatibility
Where this runs
tested against v1.9.6 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.10–3.920 runs
installs and imports cleanly · install 0.0s · import 0.078s · 19MB
glibc
py 3.10–3.920 runs
installs and imports cleanly · install 1.6s · import 0.067s · 20MB
17MB installed
● package 17MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

SVG
✓ from svgelements import SVG
✗ from svg.elements import SVG
The project was renamed from 'svg.elements' to 'svgelements' around version 0.7.6/1.0.0. Older import paths will fail.
*
✓ from svgelements import *
Commonly used for quick access to all core elements like SVG, Path, Matrix, Rect, etc.

This quickstart demonstrates how to parse an existing SVG string and iterate through its elements. It also shows how to programmatically create an SVG document with basic shapes (Rect, Group) and save it to a file or retrieve its XML as a string. The `SVG.parse()` method can take a file path, file-like object, or string stream. The `write_xml()` and `string_xml()` methods are available for generating SVG output.

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}")
Debug
Known issues
breakingThe 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 ...`.
fix
Update import statements: `from svg.elements import X` -> `from svgelements import X`.
affects: <1.0.0 (specifically pre-0.7.7)
gotchaCalculating 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`.
fix
Install `scipy` (`pip install scipy`) for exact hypergeometric calculations where applicable, which greatly speeds up `Arc.length()`.
affects: All versions
deprecatedThe `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.
fix
Adopt `SVG.write_xml(filename)` or `SVG.string_xml()` for consistent and supported SVG output generation. Review the `1.9.0` release notes for detailed changes.
affects: <1.9.0
gotchaLoading 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.
fix
Ensure `Pillow` is installed if your SVG files contain embedded images: `pip install Pillow`.
affects: All versions
gotchaThe `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.
fix
When parsing SVGs, especially those with relative units or for specific display contexts, provide accurate `width`, `height`, and `ppi` (defaults to 96) values to `SVG.parse()` to ensure correct scaling and geometry interpretation.
affects: All versions
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'svgelements'
The `svgelements` package is not installed in your current Python environment.
fix
pip install svgelements
xml.parsers.expat.ExpatError: mismatched tag: line X, column Y
The SVG file being parsed contains malformed XML syntax, such as unclosed tags, incorrect nesting, or other non-well-formed issues.
fix
Validate and correct the XML structure of your SVG file to ensure it is well-formed. Tools like online XML validators or text editors with XML linting can help.
AttributeError: 'SVG' object has no attribute 'get'
The `SVG` object in `svgelements` is not a dictionary and does not have a `get()` method for accessing elements or attributes.
fix
To access child elements, iterate through `svg.elements()` or `svg.children`. To access XML attributes of the root SVG element, use `svg.values`.
AttributeError: 'Length' object has no attribute 'units_to_pixels'
The `units_to_pixels` method on `Length` objects was deprecated and removed in newer versions of `svgelements` (post-1.0.0) in favor of the more flexible `value()` method.
fix
Use the `length_object.value(ppi=None, relative_length=None)` method for unit conversion. For example, `length_obj.value(ppi=96)`.
Upgrade
Version history
1.9.6latest on PyPI · released Aug 17, 2023
Audit
Dependencies
scipyoptionalOptional dependency for faster and more accurate Arc.length() calculations, otherwise uses geometric approximation which can be slow.
PillowoptionalSoft dependency for loading embedded images within SVG files via SVGImage objects.
Agent activity
48 hits · last 30 days
node
46
OpenAI (training)
1
Resources
svgelements — pip install svgelements · libregistry