SVG Elements Parsing

1.9.6 · active · verified Wed Apr 15

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

Install

Imports

Quickstart

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}")

view raw JSON →