svglib - SVG to ReportLab Graphics Converter

1.6.0 · active · verified Thu Apr 09

Svglib is a pure-Python library (current version 1.6.0) for reading SVG files and converting them into ReportLab Drawing objects. These objects can then be rendered to various output formats like PDF, PNG, or EPS using the ReportLab Open Source toolkit. It also includes a command-line tool, `svg2pdf`, for direct SVG to PDF conversion, offering a robust solution for integrating SVG graphics into document generation workflows.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to convert an SVG file to a ReportLab Drawing object, and then render it to both PDF and PNG formats. It requires a local 'example.svg' file to run, which is created dynamically in the code.

import os
from svglib.svglib import svg2rlg
from reportlab.graphics import renderPDF, renderPM

# Create a dummy SVG file for demonstration
dummy_svg_content = '''
<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">
  <rect x="10" y="10" width="180" height="180" fill="blue" stroke="black" stroke-width="3" />
  <text x="50" y="100" font-family="sans-serif" font-size="20" fill="white">Hello svglib!</text>
</svg>
'''
with open("example.svg", "w") as f:
    f.write(dummy_svg_content)

# Convert SVG to ReportLab Drawing object
drawing = svg2rlg("example.svg")

# Render to PDF
renderPDF.drawToFile(drawing, "example.pdf")
print("Generated example.pdf")

# Render to PNG
renderPM.drawToFile(drawing, "example.png")
print("Generated example.png")

# Clean up dummy file (optional)
os.remove("example.svg")

view raw JSON →