Skip to content

Quickstart

This guide will help you get started with svglab by demonstrating simple usage examples.

Importing the library

Start by verifying that the library is installed correctly by importing it in a Python shell or script:

import svglab

svglab has a flat import structure — this means that all symbols are available directly from the top-level package:

from svglab import Svg, Circle, Rect, Line

Parsing an SVG file

To parse an existing SVG file, use the parse_svg() function. The function returns an Svg object representing the root <svg> element of the document.

Tip

The parse_svg() function can directly read from a file-like object. See the examples below.

from svglab import parse_svg

svg_content = """
<svg width="100" height="100" xmlns="http://www.w3.org/2000/svg">
    <circle cx="50" cy="50" r="40" stroke="black" stroke-width="2" fill="red"/>
</svg>
"""

svg = parse_svg(svg_content)
print(svg)
1
2
3
4
5
from svglab import parse_svg

with open("example.svg", "r") as file:
    svg = parse_svg(file)
    print(svg)

Searching for elements

Once we have an Svg object, we can obtain a reference to the Circle element by using the find() method.

circle = svg.find("circle")
print(circle)

Modifying attributes

Element attributes are represented as properties on the element object. We can modify them directly:

Note

Attribute names that are not valid Python identifiers (e.g. stroke-width) are converted to valid identifiers by replacing hyphens with underscores (e.g. stroke_width). Reserved words are also suffixed with an underscore (e.g. class becomes class_).

1
2
3
4
from svglab import Color

circle.fill = Color("blue")  # change fill color to blue
del circle.stroke_width  # remove the stroke-width attribute

Adding new elements

New elements can be created by instantiating the corresponding class. The constructor accepts attribute values as keyword arguments. Child elements can be added using the add_child() or add_children() methods.

1
2
3
4
from svglab import Rect

rect = Rect(x=10, y=10, width=30, height=30, fill=Color("green"))
svg.add_child(rect)

Serializing the SVG

Finally, we can serialize the modified SVG back to a string using the to_xml() method. The resulting string can be saved to a file or used as needed.

Warning

Calling the __str__() method (for example, via print(svg)) will produce a human-readable representation of the object, but it is not valid XML. Always use to_xml() for serialization.

svg_xml = svg.to_xml()
print(svg_xml)

If you want to save the SVG to a file, you can do so as follows:

with open("modified_example.svg", "w") as file:
    svg.save(file)