A Python library to create SVG drawings programmatically.
Primary document management and file I/O operations for creating and saving SVG drawings. The Drawing class serves as the main entry point and container for all SVG content.
The main SVG document container and factory for all SVG elements. Acts as both document root and element creation interface.
class Drawing:
"""
Main SVG document container and factory for all SVG elements
Inherits from SVG (container) and ElementFactory (element creation)
"""
def __init__(filename="noname.svg", size=('100%', '100%'), profile='full', debug=True, **extra):
"""
Create new SVG drawing
Args:
filename: Filesystem filename for saving (default: "noname.svg")
size: 2-tuple (width, height) for document size (default: ('100%', '100%'))
profile: 'tiny' or 'full' - SVG profile specification (default: 'full')
debug: Enable element validation (default: True)
**extra: Additional SVG attributes
"""Usage Examples:
import svgwrite
# Basic drawing with default settings
dwg = svgwrite.Drawing('output.svg')
# Tiny profile for mobile/embedded use
dwg = svgwrite.Drawing('mobile.svg', profile='tiny', size=('240px', '320px'))
# Full profile with custom dimensions
dwg = svgwrite.Drawing('desktop.svg', profile='full', size=(800, 600))
# Disable validation for performance
dwg = svgwrite.Drawing('fast.svg', debug=False)Methods for saving and serializing SVG documents to various output formats.
def save(pretty=False, indent=2):
"""
Write SVG XML to the filename specified in constructor
Args:
pretty: Format XML with indentation (default: False)
indent: Number of spaces for indentation when pretty=True (default: 2)
"""
def saveas(filename, pretty=False, indent=2):
"""
Write SVG XML to specified filename
Args:
filename: Target filename for output
pretty: Format XML with indentation (default: False)
indent: Number of spaces for indentation when pretty=True (default: 2)
"""
def write(fileobj, pretty=False, indent=2):
"""
Write SVG XML to file-like object
Args:
fileobj: File-like object supporting write()
pretty: Format XML with indentation (default: False)
indent: Number of spaces for indentation when pretty=True (default: 2)
"""
def tostring():
"""
Get SVG document as XML string
Returns:
str: Complete SVG document as XML string
"""
def get_xml():
"""
Get ElementTree XML representation
Returns:
xml.etree.ElementTree.Element: Root XML element
"""Usage Examples:
import svgwrite
dwg = svgwrite.Drawing('example.svg')
dwg.add(dwg.circle((50, 50), 25, fill='blue'))
# Basic save to filename from constructor
dwg.save()
# Save with pretty formatting
dwg.save(pretty=True, indent=4)
# Save to different filename
dwg.saveas('copy.svg', pretty=True)
# Write to file object
with open('output.svg', 'w') as f:
dwg.write(f, pretty=True)
# Get as string for processing
svg_content = dwg.tostring()
print(len(svg_content)) # Check size
# Get XML tree for manipulation
xml_tree = dwg.get_xml()Methods for adding and managing child elements within the drawing.
def add(element):
"""
Add child element to the drawing
Args:
element: SVG element to add (created via factory methods)
Returns:
element: The added element for method chaining
"""
def insert(index, element):
"""
Insert element at specific position
Args:
index: Position index for insertion
element: SVG element to insert
Returns:
element: The inserted element
"""Usage Examples:
import svgwrite
dwg = svgwrite.Drawing('elements.svg')
# Create and add elements
rect = dwg.rect((10, 10), (100, 50), fill='red')
circle = dwg.circle((75, 75), 25, fill='blue')
# Add to drawing
dwg.add(rect)
dwg.add(circle)
# Method chaining
dwg.add(dwg.line((0, 0), (100, 100), stroke='black'))
# Insert at specific position
dwg.insert(0, dwg.text('Title', insert=(10, 20)))Methods for managing CSS stylesheets and font embedding within SVG documents.
def add_stylesheet(href, title, alternate="no", media="screen"):
"""
Add external stylesheet reference
Args:
href: URL or path to CSS stylesheet
title: Stylesheet title
alternate: "yes" or "no" for alternate stylesheet (default: "no")
media: CSS media type (default: "screen")
"""
def embed_stylesheet(content):
"""
Embed CSS styles directly in SVG document
Args:
content: CSS stylesheet content as string
"""
def embed_font(name, filename):
"""
Embed local font file as base64 data URI
Args:
name: Font family name for CSS reference
filename: Path to font file (TTF, OTF, WOFF, etc.)
"""
def embed_google_web_font(name, uri):
"""
Embed Google Web Font from CDN
Args:
name: Font family name
uri: Google Fonts CSS URI
"""Usage Examples:
import svgwrite
dwg = svgwrite.Drawing('styled.svg')
# Link external stylesheet
dwg.add_stylesheet('styles.css', 'Main Styles')
# Embed CSS directly
css_styles = """
.title { font-family: Arial; font-size: 24px; }
.highlight { fill: yellow; stroke: red; }
"""
dwg.embed_stylesheet(css_styles)
# Embed local font
dwg.embed_font('CustomFont', 'assets/custom.ttf')
# Use Google Fonts
dwg.embed_google_web_font(
'Roboto',
'https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;700'
)
# Use in elements
dwg.add(dwg.text('Styled Text', insert=(10, 30), class_='title'))Special method for displaying SVG content in Jupyter notebooks.
def _repr_svg_():
"""
Return SVG string for Jupyter notebook display
Returns:
str: SVG content for notebook rendering
"""Usage Examples:
# In Jupyter notebook
import svgwrite
dwg = svgwrite.Drawing(size=('200px', '100px'))
dwg.add(dwg.circle((100, 50), 40, fill='lightblue'))
# Display automatically in notebook cell
dwg # Calls _repr_svg_() automaticallyMethods for embedding external resources directly into SVG documents.
def embed_stylesheet(content):
"""
Add CSS stylesheet to defs section
Args:
content: CSS stylesheet content as string
Returns:
Style: Style element added to defs
"""
def embed_font(name, filename):
"""
Embed font file as base64 encoded data
Args:
name: Font family name for CSS font-face declaration
filename: Path to local font file (TTF, OTF, WOFF, etc.)
"""
def embed_google_web_font(name, uri):
"""
Embed Google Web Font as base64 encoded data
Args:
name: Font family name for CSS font-face declaration
uri: Google Fonts request URI (e.g., 'http://fonts.googleapis.com/css?family=Indie+Flower')
"""Usage Examples:
import svgwrite
dwg = svgwrite.Drawing('styled.svg')
# Embed custom CSS
css_content = """
.highlight { fill: yellow; stroke: red; stroke-width: 2px; }
.shadow { filter: drop-shadow(2px 2px 4px rgba(0,0,0,0.5)); }
"""
dwg.embed_stylesheet(css_content)
# Embed local font file
dwg.embed_font('CustomFont', 'fonts/custom.ttf')
# Embed Google Web Font
dwg.embed_google_web_font('IndieFlower',
'http://fonts.googleapis.com/css?family=Indie+Flower')
# Use embedded resources
styled_text = dwg.text('Styled Text', insert=(10, 50),
font_family='CustomFont', class_='highlight shadow')
dwg.add(styled_text)
web_font_text = dwg.text('Web Font Text', insert=(10, 100),
font_family='IndieFlower', font_size='24px')
dwg.add(web_font_text)Since Drawing inherits from SVG container, it supports all container operations for grouping and organizing elements.
# Inherited container methods
def g(**extra):
"""Create group container for organizing elements"""
def defs(**extra):
"""Create definitions container for reusable elements"""
def svg(insert=None, size=None, **extra):
"""Create nested SVG container"""
def symbol(**extra):
"""Create symbol definition for reuse with <use> elements"""Usage Examples:
import svgwrite
dwg = svgwrite.Drawing('organized.svg')
# Create definitions for reuse
defs = dwg.defs()
gradient = dwg.linearGradient(start=(0, 0), end=(100, 0))
gradient.add_stop_color(0, 'red')
gradient.add_stop_color(1, 'blue')
defs.add(gradient)
dwg.add(defs)
# Create groups for organization
header_group = dwg.g(id='header')
header_group.add(dwg.rect((0, 0), (200, 50), fill=gradient.get_paint_server()))
header_group.add(dwg.text('Header', insert=(10, 30)))
dwg.add(header_group)
# Nested SVG for complex layouts
nested = dwg.svg(insert=(10, 60), size=(180, 100))
nested.add(dwg.circle((90, 50), 30, fill='green'))
dwg.add(nested)Install with Tessl CLI
npx tessl i tessl/pypi-svgwrite