CairoSVG
| Language | Python (3.10+) |
|---|---|
| License | LGPL-3.0 |
| Repository | github.com/Kozea/CairoSVG |
| Documentation | cairosvg.org/documentation |
| Depends on | Cairo (C library) through cairocffi, cssselect2, tinycss2, defusedxml, Pillow |
| Read / write | read (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#
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#
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#
# 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:
cairosvg.svg2png(url="in.svg", write_to="out.png", background_color="white")
How to convert an SVG string in memory#
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#
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#
- By default CairoSVG uses defusedxml to reject XML entity attacks, limits file size and doesn’t load external files.
unsafe=True(-uon the command line) turns this off; never use it for untrusted files. negate_colors=Trueandinvert_images=Trueproduce a dark-mode version.parent_width/parent_heightresolve percentage sizes for SVG files without an absolute size.