CairoSVG
CairoSVG is a Python library that converts SVG files to other formats such as PNG, PDF, and EPS. It is built on top of the Cairo graphics library. The current version is 2.9.0, and it maintains a regular release cadence, including minor feature updates and critical security patches.
Warnings
- breaking CairoSVG frequently drops support for older Python versions. As of 2.9.0, Python 3.9 is no longer supported, requiring Python >=3.10. Earlier versions dropped support for Python 3.5, 3.6, 3.7, and 3.8.
- breaking To prevent denial-of-service (DoS) attacks, CairoSVG 2.9.0 introduced a hard limit of 100,000 recursively nested `<use>` tags. Documents exceeding this limit will stop rendering prematurely.
- breaking As of CairoSVG 2.7.0, fetching external resources (like remote images or stylesheets) from SVGs is disabled by default due to security concerns. This can lead to missing content in converted outputs if external URLs are used.
- breaking Versions prior to 2.5.1 were vulnerable to Regular Expression Denial of Service (ReDoS) attacks when processing malicious SVG files, potentially causing the process to hang indefinitely.
Install
-
pip install cairosvg -
sudo apt-get install libcairo2-dev # Debian/Ubuntu brew install cairo # macOS # Other OS may require manual Cairo installation
Imports
- svg2png
from cairosvg import svg2png
- svg2pdf
from cairosvg import svg2pdf
- svg2svg
from cairosvg import svg2svg
- svg2eps
from cairosvg import svg2eps
Quickstart
import cairosvg
import os
# Example SVG content as a byte string
svg_content_bytes = b'''
<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">
<rect x="50" y="50" width="100" height="100" fill="red" />
<circle cx="100" cy="100" r="40" fill="yellow" />
</svg>
'''
# Convert SVG to PNG and save to a file
png_output_path = "output.png"
with open(png_output_path, "wb") as f_png:
cairosvg.svg2png(bytestring=svg_content_bytes, write_to=f_png)
print(f"SVG converted to PNG: {png_output_path}")
# Convert SVG to PDF and save to a file
pdf_output_path = "output.pdf"
with open(pdf_output_path, "wb") as f_pdf:
cairosvg.svg2pdf(bytestring=svg_content_bytes, write_to=f_pdf)
print(f"SVG converted to PDF: {pdf_output_path}")
# Clean up generated files (optional)
# os.remove(png_output_path)
# os.remove(pdf_output_path)