svglib
| Language | Python (3.10+) |
|---|---|
| License | LGPL-3.0 |
| Repository | github.com/deeplook/svglib |
| Documentation | README |
| Depends on | ReportLab, lxml, Pillow, tinycss2, cssselect2 |
| Read / write | read (to ReportLab Drawing, then PDF; PNG with an extra backend) / no |
svglib reads SVG and builds a ReportLab Drawing, a vector graphics object. ReportLab can save that drawing as a PDF, or place it as a flowable inside a larger PDF document (reports, invoices, books). It needs no system libraries (all dependencies ship as wheels on PyPI), so it works where installing the Cairo C library is a problem.
It supports shapes, paths, text, transforms, <use>, clipping, linear and radial gradients (drawn as PDF shadings), CSS and embedded images, but not masks or filters. Output is sized in points: an SVG width="200" (pixels) becomes 150 points.
Installation#
pip install svglib
Basic usage: convert SVG to PDF#
from svglib.svglib import svg2rlg
from reportlab.graphics import renderPDF
drawing = svg2rlg("in.svg")
if drawing is None:
raise SystemExit("cannot parse in.svg")
print(drawing.width, drawing.height) # in points
renderPDF.drawToFile(drawing, "out.pdf")
svg2rlg also reads .svgz files and accepts a file object or pathlib.Path. The package installs an svg2pdf command: svg2pdf in.svg.
How to scale an SVG drawing#
from svglib.svglib import svg2rlg
from reportlab.graphics import renderPDF
drawing = svg2rlg("in.svg")
factor = 2.0
drawing.width *= factor
drawing.height *= factor
drawing.scale(factor, factor)
renderPDF.drawToFile(drawing, "out-2x.pdf")
How to put an SVG into a ReportLab PDF document#
A Drawing is a flowable, so it goes into a Platypus story like a paragraph:
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.platypus import Paragraph, SimpleDocTemplate
from svglib.svglib import svg2rlg
doc = SimpleDocTemplate("report.pdf", pagesize=A4)
story = [
Paragraph("Sales chart", getSampleStyleSheet()["Heading1"]),
svg2rlg("chart.svg"),
]
doc.build(story)
Or draw it at a position on a canvas with renderPDF.draw(drawing, canvas, x, y).
How to convert SVG to PNG#
ReportLab’s bitmap renderer needs the rlPyCairo backend (which needs Cairo):
pip install rlPyCairo
from reportlab.graphics import renderPM
renderPM.drawToFile(drawing, "out.png", fmt="PNG", dpi=144)
If you need PNG output, CairoSVG renders more SVG features.
How to load untrusted SVG#
XML entities aren’t resolved by default (resolve_entities=False). Restrict external <image> and <use> references to a directory you trust:
drawing = svg2rlg("upload.svg", external_reference_root="/srv/app/svg-assets")
Tips#
- Text uses ReportLab’s fonts; register TrueType fonts with
reportlab.pdfbase.pdfmetrics.registerFontto match the SVG’sfont-family. svg2rlgreturnsNone(and logs an error) when it can’t parse the file.