rsvg with Python 3.2 on Ubuntu

∥☆過路亽.° 提交于 2019-11-29 07:14:33

I experienced a lot of difficulty trying to figure out how to do this. I hope others find this answer and save themselves a lot of time!

For Python 3, Python language bindings for several libraries originally written in C (including GTK, Clutter, and librsvg) have been replaced by GObject introspection libraries, Python code which dynamically generates Python objects from C "objects".

In order to use librsvg on Python 3, first install the necessary GObject introspection libraries (in addition to the Python 3 Cairo library). For example, on Ubuntu 13.10:

sudo apt-get install gir1.2-rsvg-2.0 python3-cairo

Then test it out with the following code.

#!/usr/bin/env python3                                                          

# `gi.repository` is a special Python package that dynamically generates objects 
from gi.repository import Rsvg
import cairo

INPUTFILE = 'tiger.svg'

if __name__ == '__main__':
    # create the cairo context                                                  
    surface = cairo.SVGSurface('myoutput.svg', 580, 530)
    context = cairo.Context(surface)

    # use rsvg to render the cairo context                                      
    handle = Rsvg.Handle()
    svg = handle.new_from_file(INPUTFILE)
    svg.render_cairo(context)

In order to implement this for your project,

  1. change cairo.SVGSurface to be whatever surface you are going to draw on, and
  2. modify the value of INPUTFILE to be the name of the SVG file you wish to render.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!