CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-svgwrite

A Python library to create SVG drawings programmatically.

Overview
Eval results
Files

shapes.mddocs/

Shape Creation

Comprehensive set of SVG shape elements including basic geometric shapes, complex paths, and polylines with full styling and transformation support.

Capabilities

Basic Shapes

Fundamental geometric shapes that form the building blocks of SVG graphics.

def line(start=(0,0), end=(0,0), **extra):
    """
    Create line segment between two points
    
    Args:
        start: Starting point as (x, y) tuple (default: (0,0))
        end: Ending point as (x, y) tuple (default: (0,0))
        **extra: Additional SVG attributes (stroke, stroke-width, etc.)
    
    Returns:
        Line: Line element with Transform, Presentation, and Markers mixins
    """

def rect(insert=(0,0), size=(1,1), rx=None, ry=None, **extra):
    """
    Create axis-aligned rectangle with optional rounded corners
    
    Args:
        insert: Top-left corner position as (x, y) tuple (default: (0,0))
        size: Rectangle dimensions as (width, height) tuple (default: (1,1))
        rx: Horizontal corner radius (default: None)
        ry: Vertical corner radius (default: None)
        **extra: Additional SVG attributes (fill, stroke, etc.)
    
    Returns:
        Rect: Rectangle element with Transform and Presentation mixins
    """

def circle(center=(0,0), r=1, **extra):
    """
    Create circle based on center point and radius
    
    Args:
        center: Center point as (x, y) tuple (default: (0,0))
        r: Circle radius (default: 1)
        **extra: Additional SVG attributes (fill, stroke, etc.)
    
    Returns:
        Circle: Circle element with Transform and Presentation mixins
    """

def ellipse(center=(0,0), r=(1,1), **extra):
    """
    Create axis-aligned ellipse with two radii
    
    Args:
        center: Center point as (x, y) tuple (default: (0,0))
        r: Radii as (rx, ry) tuple or single value (default: (1,1))
        **extra: Additional SVG attributes (fill, stroke, etc.)
    
    Returns:
        Ellipse: Ellipse element with Transform and Presentation mixins
    """

Usage Examples:

import svgwrite

dwg = svgwrite.Drawing('shapes.svg', size=('300px', '200px'))

# Basic line with styling
line = dwg.line(start=(10, 10), end=(100, 50), stroke='black', stroke_width=2)
dwg.add(line)

# Rectangle with rounded corners
rect = dwg.rect(insert=(20, 60), size=(80, 40), rx=5, ry=5, 
                fill='lightblue', stroke='navy', stroke_width=1)
dwg.add(rect)

# Simple circle
circle = dwg.circle(center=(150, 50), r=25, fill='red', fill_opacity=0.7)
dwg.add(circle)

# Ellipse with different radii
ellipse = dwg.ellipse(center=(200, 100), r=(40, 20), 
                      fill='green', stroke='darkgreen')
dwg.add(ellipse)

# Using units for precise sizing
rect_cm = dwg.rect(insert=(10*svgwrite.mm, 120), size=(5*svgwrite.cm, 2*svgwrite.cm), 
                   fill='yellow')
dwg.add(rect_cm)

Polylines and Polygons

Multi-point shapes for creating complex connected line segments and closed shapes.

def polyline(points=[], **extra):
    """
    Create connected line segments (open shape)
    
    Args:
        points: List of points as [(x1,y1), (x2,y2), ...] (default: [])
        **extra: Additional SVG attributes (stroke, fill, etc.)
    
    Returns:
        Polyline: Polyline element with Transform, Presentation, and Markers mixins
    """

def polygon(points=[], **extra):
    """
    Create closed shape from connected line segments
    
    Args:
        points: List of points as [(x1,y1), (x2,y2), ...] (default: [])
        **extra: Additional SVG attributes (fill, stroke, etc.)
    
    Returns:
        Polygon: Polygon element inheriting from Polyline
    """

# Utility method for point string conversion
def points_to_string(points):
    """
    Convert point list to SVG points attribute string
    
    Args:
        points: List of (x, y) coordinate tuples
    
    Returns:
        str: Space-separated coordinate pairs
    """

Usage Examples:

import svgwrite

dwg = svgwrite.Drawing('polyshapes.svg', size=('400px', '300px'))

# Polyline - open path
zigzag_points = [(10, 50), (50, 10), (90, 50), (130, 10), (170, 50)]
polyline = dwg.polyline(points=zigzag_points, 
                        stroke='blue', stroke_width=3, fill='none')
dwg.add(polyline)

# Polygon - closed shape
triangle_points = [(200, 20), (250, 80), (150, 80)]
triangle = dwg.polygon(points=triangle_points, 
                       fill='orange', stroke='red', stroke_width=2)
dwg.add(triangle)

# Complex polygon - star shape
star_points = [(300, 50), (310, 80), (340, 80), (320, 100), 
               (330, 130), (300, 115), (270, 130), (280, 100), 
               (260, 80), (290, 80)]
star = dwg.polygon(points=star_points, fill='gold', stroke='orange')
dwg.add(star)

# House shape
house_points = [(50, 200), (50, 150), (75, 130), (100, 150), 
                (100, 200), (50, 200)]
house = dwg.polyline(points=house_points, 
                     stroke='black', stroke_width=2, fill='lightgreen')
dwg.add(house)

Path Elements

Advanced path elements for creating complex shapes using SVG path commands and coordinates.

def path(d=None, **extra):
    """
    Create path element for complex shapes using SVG path data
    
    Args:
        d: SVG path data string or None (default: None)
        **extra: Additional SVG attributes (fill, stroke, etc.)
    
    Returns:
        Path: Path element with Transform, Presentation, and Markers mixins
    """

# Path methods for building commands
def push(*elements):
    """
    Add path commands and coordinates to path data
    
    Args:
        *elements: Path commands and coordinates to append
    """

def push_arc(target, rotation, r, large_arc=True, angle_dir='+', absolute=False):
    """
    Add elliptical arc command to path
    
    Args:
        target: End point coordinates (x, y)
        rotation: X-axis rotation angle in degrees
        r: Radii as (rx, ry) tuple
        large_arc: Use large arc sweep (default: True)
        angle_dir: Arc direction '+' or '-' (default: '+')
        absolute: Use absolute coordinates (default: False)
    """

@staticmethod
def arc_flags(large_arc=True, angle_dir='+'):
    """
    Generate arc flags for elliptical arc commands
    
    Args:
        large_arc: Use large arc sweep (default: True)
        angle_dir: Arc direction '+' or '-' (default: '+')
    
    Returns:
        tuple: (large_arc_flag, sweep_flag) for SVG arc command
    """

Usage Examples:

import svgwrite

dwg = svgwrite.Drawing('paths.svg', size=('400px', '300px'))

# Simple path with basic commands
simple_path = dwg.path(d='M 10,50 L 50,10 L 90,50 Z', 
                       fill='lightblue', stroke='navy')
dwg.add(simple_path)

# Building path programmatically
complex_path = dwg.path(fill='none', stroke='red', stroke_width=2)
complex_path.push('M', 100, 50)  # Move to
complex_path.push('L', 150, 20)  # Line to
complex_path.push('Q', 180, 50, 150, 80)  # Quadratic curve
complex_path.push('Z')  # Close path
dwg.add(complex_path)

# Path with arc
arc_path = dwg.path(fill='yellow', stroke='orange', stroke_width=3)
arc_path.push('M', 200, 100)  # Start point
arc_path.push_arc(
    target=(250, 50),     # End point
    rotation=0,           # No rotation
    r=(30, 20),          # Ellipse radii
    large_arc=False,      # Small arc
    angle_dir='+'         # Clockwise
)
arc_path.push('Z')  # Close path
dwg.add(arc_path)

# Complex curved path
bezier_path = dwg.path(d='''
    M 50,150 
    C 50,100 100,100 100,150
    C 100,200 150,200 150,150
    C 150,100 200,100 200,150
''', fill='none', stroke='purple', stroke_width=4)
dwg.add(bezier_path)

Shape Transformations

All shape elements support transformation methods through the Transform mixin.

# Transform mixin methods available on all shapes
def translate(tx, ty=None):
    """Add translation transform to element"""

def rotate(angle, center=None):
    """Add rotation transform around optional center point"""

def scale(sx, sy=None):
    """Add scale transform with separate x and y factors"""

def skewX(angle):
    """Add X-axis skew transformation"""

def skewY(angle):
    """Add Y-axis skew transformation"""

def matrix(a, b, c, d, e, f):
    """Add custom transformation matrix"""

Usage Examples:

import svgwrite

dwg = svgwrite.Drawing('transforms.svg', size=('400px', '300px'))

# Basic rectangle for transformation
base_rect = dwg.rect(insert=(50, 50), size=(60, 40), fill='lightcoral')

# Translated rectangle
translated = dwg.rect(insert=(50, 50), size=(60, 40), fill='lightblue')
translated.translate(100, 0)  # Move right
dwg.add(translated)

# Rotated rectangle
rotated = dwg.rect(insert=(50, 50), size=(60, 40), fill='lightgreen')
rotated.rotate(45, center=(80, 70))  # Rotate around center
dwg.add(rotated)

# Scaled rectangle
scaled = dwg.rect(insert=(50, 50), size=(60, 40), fill='lightyellow')
scaled.scale(1.5, 0.8)  # Scale width and height differently
scaled.translate(200, 100)
dwg.add(scaled)

# Combine multiple transformations
multi_transform = dwg.circle(center=(300, 150), r=20, fill='orange')
multi_transform.translate(50, -50)
multi_transform.rotate(30)
multi_transform.scale(1.2)
dwg.add(multi_transform)

# Add base rectangle last to show original position
dwg.add(base_rect)

Presentation Attributes

All shapes support comprehensive styling through the Presentation mixin.

# Common presentation attributes available on all shapes
fill='color'              # Fill color
stroke='color'            # Stroke color
stroke_width='length'     # Stroke width
stroke_dasharray='list'   # Dash pattern
stroke_opacity='number'   # Stroke transparency
fill_opacity='number'     # Fill transparency
opacity='number'          # Overall transparency

Usage Examples:

import svgwrite

dwg = svgwrite.Drawing('styling.svg', size=('500px', '200px'))

# Gradient-like effect with opacity
for i in range(10):
    alpha = 1.0 - (i * 0.1)
    circle = dwg.circle(center=(50 + i*5, 100), r=30, 
                        fill='blue', fill_opacity=alpha)
    dwg.add(circle)

# Dashed lines with different patterns
patterns = ['5,5', '10,2,2,2', '15,5,5,5', '20,10']
for i, pattern in enumerate(patterns):
    line = dwg.line(start=(150, 30 + i*30), end=(300, 30 + i*30),
                    stroke='red', stroke_width=3, stroke_dasharray=pattern)
    dwg.add(line)

# Styled shapes with various effects
styled_rect = dwg.rect(insert=(350, 50), size=(100, 80),
                       fill='lightgreen', stroke='darkgreen', stroke_width=4,
                       stroke_dasharray='8,3', fill_opacity=0.6, rx=10)
dwg.add(styled_rect)

Image Elements

Embed raster or vector images within SVG drawings using external references or base64 data.

def image(href, insert=None, size=None, **extra):
    """
    Create image element that renders external image files
    
    Args:
        href: Hyperlink to image resource (URL or data URI)
        insert: Top-left corner position as (x, y) tuple
        size: Image dimensions as (width, height) tuple
        **extra: Additional SVG attributes
    
    Returns:
        Image: Image element with Transform and Clipping mixins
    """

Image Methods:

def stretch():
    """
    Stretch image to fill viewport without preserving aspect ratio
    Sets preserveAspectRatio='none'
    """

def fit(horiz="center", vert="middle", scale="meet"):
    """
    Configure image aspect ratio preservation and alignment
    
    Args:
        horiz: Horizontal alignment ('left'|'center'|'right')
        vert: Vertical alignment ('top'|'middle'|'bottom')  
        scale: Scale method ('meet'|'slice')
            - 'meet': preserve aspect ratio, zoom to fit viewport
            - 'slice': preserve aspect ratio, fill viewport (may crop)
    """

Usage Examples:

import svgwrite

dwg = svgwrite.Drawing('images.svg', size=('600px', '400px'))

# External image reference
photo = dwg.image('https://example.com/photo.jpg', 
                  insert=(10, 10), size=(200, 150))
dwg.add(photo)

# Local image file
local_img = dwg.image('assets/logo.png', 
                      insert=(250, 10), size=(100, 100))
dwg.add(local_img)

# Base64 embedded image
data_uri = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg=='
pixel = dwg.image(data_uri, insert=(400, 50), size=(50, 50))
dwg.add(pixel)

# Image with aspect ratio control
fitted_img = dwg.image('landscape.jpg', insert=(10, 200), size=(280, 160))
fitted_img.fit(horiz='left', vert='top', scale='meet')
dwg.add(fitted_img)

# Stretched image (ignores aspect ratio)
stretched = dwg.image('square.jpg', insert=(320, 200), size=(200, 100))
stretched.stretch()
dwg.add(stretched)

# SVG as image
svg_img = dwg.image('vector-graphic.svg', insert=(50, 320), size=(150, 60))
dwg.add(svg_img)

Install with Tessl CLI

npx tessl i tessl/pypi-svgwrite

docs

advanced.md

core.md

index.md

shapes.md

text.md

utilities.md

tile.json