A Simple SVG Converter based on Cairo that converts SVG files to PDF, EPS, PostScript, and PNG formats
npx @tessl/cli install tessl/pypi-cairosvg@2.8.0A Simple SVG Converter based on Cairo that converts SVG files to PDF, EPS, PostScript (PS), and PNG formats. CairoSVG provides both a Python API and command-line interface for programmatic and terminal usage, supporting SVG 1.1 specification with comprehensive CSS styling, gradient fills, patterns, and text rendering capabilities.
pip install CairoSVGimport cairosvgFor direct access to conversion functions:
from cairosvg import svg2pdf, svg2png, svg2ps, svg2eps, svg2svgFor access to Surface classes:
from cairosvg import SURFACES
from cairosvg.surface import Surface, PDFSurface, PNGSurface, PSSurface, EPSSurface, SVGSurfaceimport cairosvg
# Convert SVG file to PDF
cairosvg.svg2pdf(url='image.svg', write_to='output.pdf')
# Convert SVG file to PNG with custom DPI
cairosvg.svg2png(url='image.svg', write_to='output.png', dpi=150)
# Convert SVG string to PDF bytes
svg_string = '''<svg width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="50" cy="50" r="40" fill="red"/>
</svg>'''
pdf_bytes = cairosvg.svg2pdf(bytestring=svg_string.encode('utf-8'))
# Convert with file objects
with open('input.svg', 'rb') as svg_file:
with open('output.png', 'wb') as png_file:
cairosvg.svg2png(file_obj=svg_file, write_to=png_file, dpi=300)Converts SVG files to PDF format with vector graphics preservation.
def svg2pdf(bytestring=None, *, file_obj=None, url=None, dpi=96,
parent_width=None, parent_height=None, scale=1, unsafe=False,
background_color=None, negate_colors=False, invert_images=False,
write_to=None, output_width=None, output_height=None):
"""
Convert an SVG document to PDF format.
Parameters:
- bytestring (bytes, optional): The SVG source as a byte-string
- file_obj (file-like, optional): A file-like object containing SVG data
- url (str, optional): A filename or URL to an SVG file
- dpi (float): The ratio between 1 inch and 1 pixel (default: 96)
- parent_width (float, optional): The width of the parent container in pixels
- parent_height (float, optional): The height of the parent container in pixels
- scale (float): The output scaling factor (default: 1)
- unsafe (bool): Allow external file access, XML entities and very large files (default: False)
- background_color (str, optional): Background color for the output
- negate_colors (bool): Replace every vector color with its complement (default: False)
- invert_images (bool): Replace every raster pixel with its complementary color (default: False)
- write_to (str or file-like, optional): Output filename or file-like object
- output_width (float, optional): Desired output width in pixels
- output_height (float, optional): Desired output height in pixels
Returns:
bytes: PDF data if write_to is None, otherwise None
"""Converts SVG files to PNG raster format with customizable resolution.
def svg2png(bytestring=None, *, file_obj=None, url=None, dpi=96,
parent_width=None, parent_height=None, scale=1, unsafe=False,
background_color=None, negate_colors=False, invert_images=False,
write_to=None, output_width=None, output_height=None):
"""
Convert an SVG document to PNG format.
Parameters:
- bytestring (bytes, optional): The SVG source as a byte-string
- file_obj (file-like, optional): A file-like object containing SVG data
- url (str, optional): A filename or URL to an SVG file
- dpi (float): The ratio between 1 inch and 1 pixel (default: 96)
- parent_width (float, optional): The width of the parent container in pixels
- parent_height (float, optional): The height of the parent container in pixels
- scale (float): The output scaling factor (default: 1)
- unsafe (bool): Allow external file access, XML entities and very large files (default: False)
- background_color (str, optional): Background color for the output
- negate_colors (bool): Replace every vector color with its complement (default: False)
- invert_images (bool): Replace every raster pixel with its complementary color (default: False)
- write_to (str or file-like, optional): Output filename or file-like object
- output_width (float, optional): Desired output width in pixels
- output_height (float, optional): Desired output height in pixels
Returns:
bytes: PNG data if write_to is None, otherwise None
"""Converts SVG files to PostScript format for printing and publishing.
def svg2ps(bytestring=None, *, file_obj=None, url=None, dpi=96,
parent_width=None, parent_height=None, scale=1, unsafe=False,
background_color=None, negate_colors=False, invert_images=False,
write_to=None, output_width=None, output_height=None):
"""
Convert an SVG document to PostScript format.
Parameters:
- bytestring (bytes, optional): The SVG source as a byte-string
- file_obj (file-like, optional): A file-like object containing SVG data
- url (str, optional): A filename or URL to an SVG file
- dpi (float): The ratio between 1 inch and 1 pixel (default: 96)
- parent_width (float, optional): The width of the parent container in pixels
- parent_height (float, optional): The height of the parent container in pixels
- scale (float): The output scaling factor (default: 1)
- unsafe (bool): Allow external file access, XML entities and very large files (default: False)
- background_color (str, optional): Background color for the output
- negate_colors (bool): Replace every vector color with its complement (default: False)
- invert_images (bool): Replace every raster pixel with its complementary color (default: False)
- write_to (str or file-like, optional): Output filename or file-like object
- output_width (float, optional): Desired output width in pixels
- output_height (float, optional): Desired output height in pixels
Returns:
bytes: PostScript data if write_to is None, otherwise None
"""Converts SVG files to Encapsulated PostScript format for document embedding.
def svg2eps(bytestring=None, *, file_obj=None, url=None, dpi=96,
parent_width=None, parent_height=None, scale=1, unsafe=False,
background_color=None, negate_colors=False, invert_images=False,
write_to=None, output_width=None, output_height=None):
"""
Convert an SVG document to Encapsulated PostScript format.
Parameters:
- bytestring (bytes, optional): The SVG source as a byte-string
- file_obj (file-like, optional): A file-like object containing SVG data
- url (str, optional): A filename or URL to an SVG file
- dpi (float): The ratio between 1 inch and 1 pixel (default: 96)
- parent_width (float, optional): The width of the parent container in pixels
- parent_height (float, optional): The height of the parent container in pixels
- scale (float): The output scaling factor (default: 1)
- unsafe (bool): Allow external file access, XML entities and very large files (default: False)
- background_color (str, optional): Background color for the output
- negate_colors (bool): Replace every vector color with its complement (default: False)
- invert_images (bool): Replace every raster pixel with its complementary color (default: False)
- write_to (str or file-like, optional): Output filename or file-like object
- output_width (float, optional): Desired output width in pixels
- output_height (float, optional): Desired output height in pixels
Returns:
bytes: EPS data if write_to is None, otherwise None
"""Converts and processes SVG files to normalized SVG format.
def svg2svg(bytestring=None, *, file_obj=None, url=None, dpi=96,
parent_width=None, parent_height=None, scale=1, unsafe=False,
background_color=None, negate_colors=False, invert_images=False,
write_to=None, output_width=None, output_height=None):
"""
Convert an SVG document to SVG format (normalization/processing).
Parameters:
- bytestring (bytes, optional): The SVG source as a byte-string
- file_obj (file-like, optional): A file-like object containing SVG data
- url (str, optional): A filename or URL to an SVG file
- dpi (float): The ratio between 1 inch and 1 pixel (default: 96)
- parent_width (float, optional): The width of the parent container in pixels
- parent_height (float, optional): The height of the parent container in pixels
- scale (float): The output scaling factor (default: 1)
- unsafe (bool): Allow external file access, XML entities and very large files (default: False)
- background_color (str, optional): Background color for the output
- negate_colors (bool): Replace every vector color with its complement (default: False)
- invert_images (bool): Replace every raster pixel with its complementary color (default: False)
- write_to (str or file-like, optional): Output filename or file-like object
- output_width (float, optional): Desired output width in pixels
- output_height (float, optional): Desired output height in pixels
Returns:
bytes: SVG data if write_to is None, otherwise None
"""For advanced usage and fine-grained control over the conversion process, you can use Surface classes directly.
class Surface:
"""
Abstract base class for CairoSVG surfaces.
The width and height attributes are in device units (pixels for PNG, else points).
The context_width and context_height attributes are in user units (i.e. in pixels).
"""
@classmethod
def convert(cls, bytestring=None, *, file_obj=None, url=None, dpi=96,
parent_width=None, parent_height=None, scale=1, unsafe=False,
background_color=None, negate_colors=False,
invert_images=False, write_to=None, output_width=None,
output_height=None, **kwargs):
"""Convert an SVG document to the format for this class."""
def __init__(self, tree, output, dpi, parent_surface=None,
parent_width=None, parent_height=None,
scale=1, output_width=None, output_height=None,
background_color=None, map_rgba=None, map_image=None):
"""Create the surface from a filename or a file-like object."""
def finish(self):
"""Read the surface content."""
def draw(self, node):
"""Draw node and its children."""
@property
def points_per_pixel(self):
"""Surface resolution."""
@property
def device_units_per_user_units(self):
"""Ratio between Cairo device units and user units."""class PDFSurface(Surface):
"""A surface that writes in PDF format."""
class PSSurface(Surface):
"""A surface that writes in PostScript format."""
class EPSSurface(Surface):
"""A surface that writes in Encapsulated PostScript format."""
class PNGSurface(Surface):
"""A surface that writes in PNG format."""
class SVGSurface(Surface):
"""A surface that writes in SVG format."""For advanced SVG parsing and tree manipulation:
class Tree:
"""SVG tree parser class."""
def __new__(cls, **kwargs):
"""Create a new Tree instance."""
class Node:
"""SVG node parser class."""VERSION: str
__version__: str # Same as VERSION
SURFACES: dict # Mapping of format names to Surface classesclass PointError(Exception):
"""Exception raised when parsing a point fails."""CairoSVG can also be used from the command line:
# Convert SVG to PDF
cairosvg input.svg -o output.pdf
# Convert with specific format
cairosvg input.svg -f png -o output.png
# Convert with custom DPI
cairosvg input.svg -f png -d 300 -o output.png
# Convert with custom dimensions
cairosvg input.svg -f png -W 800 -H 600 -o output.png
# Convert from stdin to stdout
cat input.svg | cairosvg -f pdf > output.pdffrom cairosvg import svg2pdf, PointError
try:
svg2pdf(url='malformed.svg', write_to='output.pdf')
except PointError as e:
print(f"SVG parsing error: {e}")
except ValueError as e:
print(f"Invalid SVG dimensions: {e}")
except FileNotFoundError as e:
print(f"File not found: {e}")unsafe=True parameter allows external file access, XML entities, and very large files. This can make your application vulnerable to XXE attacks and various DoS attacks. Only use when you trust the SVG source.