Ubuntu 18 中python-rsvg使用方法及Python2替代方案咨询
Got it, let's work through this problem you're facing with rendering SVGs to a pycairo context in Python 2 on Ubuntu 18.04—since the python-rsvg package is unavailable, here are two reliable alternatives that should fit your needs:
1. Use GObject Introspection Bindings for librsvg (Recommended)
This is the closest drop-in replacement for python-rsvg, as it uses the same underlying librsvg library but with modern GObject introspection bindings (officially supported on Ubuntu 18.04).
Step 1: Install Dependencies
First, set up the required system packages:
sudo apt-get update sudo apt-get install gir1.2-rsvg-2.0 python-gi python-cairo
Step 2: Update Your Code
The API is nearly identical to the old python-rsvg, so you can adjust your code with minimal changes:
from gi.repository import Rsvg import cairo # Set up your cairo context as you did before context = cairo.Context(your_surface) # Load the SVG file (matches the pattern of rsvg.Handle) svg_handle = Rsvg.Handle.new_from_file(path_to_svg_file) # Render directly to the cairo context svg_handle.render_cairo(context)
This will behave exactly like your original code, since it relies on the same librsvg backend for rendering.
2. Use CairoSVG (Pure Python Alternative)
If you can't install system-level libraries for some reason, CairoSVG is a pure-Python SVG renderer that supports rendering directly to a pycairo context. Note you'll need a Python 2-compatible version (version 2.x is the last series supporting Python 2.7).
Step 1: Install CairoSVG
Use pip2 to install the compatible version:
pip2 install cairosvg==2.5.2
Step 2: Adjust Your Code
The API is a bit different but still straightforward:
import cairosvg import cairo # Set up your cairo context context = cairo.Context(your_surface) # Render the SVG file directly to the context with open(path_to_svg_file, 'rb') as svg_file: cairosvg.svg2cairo(svg_file, context)
Keep in mind that CairoSVG's SVG parsing/rendering might have minor differences from librsvg, but it works well for most common SVG use cases.
内容的提问来源于stack exchange,提问作者morgen

