CairoSVG

2.9.0 · active · verified Thu Apr 09

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

Install

Imports

Quickstart

This quickstart demonstrates how to convert a simple SVG byte string to a PNG and a PDF file using `cairosvg.svg2png` and `cairosvg.svg2pdf`. The `bytestring` parameter expects bytes, and `write_to` expects a file-like object open in binary write mode.

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)

view raw JSON →