Search code examples
pythonsvgrendering

Python render svg image with the python only modules


The question is simple, but I have googled a lot of methods, and there no such solution as:

import svg-render-library
figure = svg-render-library.open('test.svg')
figure.render()

Is there any simple methods to display an SVG image using only python libraries? I am asking about rendering the SVG image without any conversion to another formats and to render using pure python, without any 3rd party software. As I have tried, this seems impossible for now.

As built-in python I mean - only python packages available through pip, so it is not necessary to install/compile anything else. And to render I mean to show inside window which part of the python, not the browser or any external software.

At least I have currently working solution my question on Stack Overflow.


Solution

  • Currently, there is no method to render natively cross-platform with just the standard library (ie. some python distributions for OSX do not include tkinter by default). Ergo, there is no good way to do this.

    AFAIK, there are no other ways to do this maintaining your described API without writing your own code or reaching out to non-standard library modules.

    If you still are 100% set on doing it with pure python and the standard library, you have tkinter, and don't care about writing your own implementation, then proceed.

    If you are talking about rendering in the context of displaying an SVG in a window, then your best bet would be to utilize the tkinter and xml modules.

    SVG is just an XML file, so xml.minidom should be able to parse an svg file. You can then extract the height and width from the dom, draw each element onto a tkinter.Canvas widget, and then have tkinter render the window. You will need to either pre-calculate transparencies or handle that while managing the layering.

    Another option is to use the turtle package which wraps around tkinter. If the SVG is just a path, then this should be able to draw that path fairly straight forward.

    If you are willing to reach out beyond the standard library, then cairosvg or svglib both can easily handle this task. cairosvg is a bit of a bear if you aren't used to installing system libraries, but svglib is a pure python implementation.