svglib - SVG to ReportLab Graphics Converter
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
- breaking Older versions (prior to 0.9.4) were vulnerable to XML External Entity (XXE) Injection. Ensure you are using a patched version (0.9.4 or higher) to avoid security risks.
- gotcha Svglib does not support all SVG features due to limitations in the underlying ReportLab library. Specifically, color gradients, patterns, markers, clipping paths (beyond single paths), `textPath`, and `ForeignObject` elements are not supported. This can lead to unexpected rendering or missing elements in the output.
- gotcha CSS `@import` rules within SVG stylesheets are ignored by `svglib`. While versions 1.5.0+ avoid crashing, the imported styles will simply not be applied.
- breaking Upgrading `svglib` from very old versions (e.g., 0.8.1 to 0.9.2) could lead to SVG images being rendered in black and white or encountering font errors in the output PDF.
- deprecated Support for Python 3.8 was dropped in `svglib` 1.6.0. Users on older Python environments will need to use an earlier `svglib` version.
Install
-
pip install svglib
Imports
- svg2rlg
from svglib.svglib import svg2rlg
- renderPDF
from reportlab.graphics import renderPDF
- renderPM
from reportlab.graphics import renderPM
Quickstart
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")