All formats

CairoSVG

LanguagePython (3.10+)
LicenseLGPL-3.0
Repositorygithub.com/Kozea/CairoSVG
Documentationcairosvg.org/documentation
Depends onCairo (C library) through cairocffi, cssselect2, tinycss2, defusedxml, Pillow
Read / writeread (converts to PNG, PDF, PS, EPS and cleaned SVG) / no

CairoSVG parses SVG with its own Python code and draws it with Cairo. It supports most of SVG 1.1 static rendering: shapes, paths, text, gradients, patterns, clipping, masks, markers, <use>, CSS and some filters. It’s made by the authors of WeasyPrint, and is widely used to rasterize icons and badges and to turn SVG charts into PDF.

It has 5 functions with the same arguments: svg2png, svg2pdf, svg2ps, svg2eps and svg2svg, plus a cairosvg command line tool.

Installation#

Shell
pip install cairosvg

The Cairo C library must also be installed: it comes with most Linux desktops (sudo apt install libcairo2) and Homebrew (brew install cairo). On Windows install the GTK runtime or MSYS2’s mingw-w64-x86_64-cairo and make sure libcairo-2.dll is on the PATH, or you get OSError: no library called "cairo-2" was found.

Basic usage: convert SVG to PNG and PDF#

Python
import cairosvg

cairosvg.svg2png(url="in.svg", write_to="out.png")
cairosvg.svg2pdf(url="in.svg", write_to="out.pdf")

url accepts a file path or URL. Instead of url you can pass file_obj (an open file) or bytestring (SVG as bytes or str). Without write_to, the functions return the output as bytes.

How to set the output size of a PNG#

Python
# exact width; height follows the aspect ratio
cairosvg.svg2png(url="in.svg", write_to="out-512.png", output_width=512)

# twice the intrinsic size
cairosvg.svg2png(url="in.svg", write_to="out@2x.png", scale=2)

# physical units (mm, in, pt) at 300 DPI
cairosvg.svg2png(url="print.svg", write_to="print.png", dpi=300)

How to add a background color#

PNG output is transparent by default:

Python
cairosvg.svg2png(url="in.svg", write_to="out.png", background_color="white")

How to convert an SVG string in memory#

Python
import cairosvg

svg = b'<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><circle cx="50" cy="50" r="40" fill="orange"/></svg>'
png_bytes = cairosvg.svg2png(bytestring=svg)

with open("circle.png", "wb") as f:
    f.write(png_bytes)

How to convert from the command line#

Shell
cairosvg in.svg -o out.pdf
cairosvg in.svg -o out.png --output-width 512
cairosvg in.svg -f png -s 2 -o out@2x.png

Tips#