svgpathtools

1.7.2 · active · verified Thu Apr 16

svgpathtools is a Python library (version 1.7.2) for manipulating and analyzing SVG Path objects and Bézier curves. It offers functions to read, write, and display SVG files, convert Bézier segments to polynomials, compute tangents, curvature, intersections, and perform various geometric transformations. It is actively maintained with releases as needed.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to read paths from an SVG file, modify an existing path (e.g., scaling it), create a new path using segment classes (Line, CubicBezier), and then write all paths to a new SVG file. Coordinates are handled as complex numbers (x + yj).

from svgpathtools import svg2paths, wsvg, Path, Line, CubicBezier
import os

# Create a dummy SVG file for demonstration
with open('example.svg', 'w') as f:
    f.write('<svg width="200" height="200">')
    f.write('<path d="M10 10 L100 10 L100 100 L10 100 Z" fill="blue"/>')
    f.write('</svg>')

# 1. Read paths from an existing SVG file
paths, attributes = svg2paths('example.svg')
print(f"Read {len(paths)} path(s) from example.svg")

# 2. Manipulate a path (e.g., scale the first path)
if paths:
    original_path = paths[0]
    # Scale the path by 0.5
    scaled_path = original_path.scaled(0.5)
    paths[0] = scaled_path
    print(f"Scaled the first path. New length: {scaled_path.length():.2f}")

# 3. Create a new path programmatically
new_segment1 = Line(start=10+10j, end=50+100j)
new_segment2 = CubicBezier(start=50+100j, control1=150+50j, control2=50+150j, end=150+100j)
new_path = Path(new_segment1, new_segment2)

# Add the new path to the list and assign attributes
paths.append(new_path)
attributes.append({'fill': 'red', 'stroke': 'black', 'stroke-width': '2'})

# 4. Write the modified and new paths to a new SVG file
wsvg(paths, attributes=attributes, filename='output.svg', openinbrowser=False)
print("Modified paths written to output.svg")

# Clean up dummy file (optional)
os.remove('example.svg')
# os.remove('output.svg') # Uncomment to remove output file after inspection

view raw JSON →