pygtk / rsvg - getting size of drawing?

810 Views Asked by At

Is it possible for RSVG and Cairo to find the extents of a drawing within an SVG image?

i.e. not the page width/height, but the space actually used by drawing elements.

This doesn't work, it just returns page size:

 img = rsvg.Handle(file="myfile.svg")
 (w, h, w2,h2) = svg.get_dimension_data() # gives document's declared size

This doesn't seem to return any information about size:

 svg.render_cairo(context) # returns None

This doesn't work, it also returns the page size:

 self.svg.get_pixbuf().get_width()

This is with pygtk-all-in-one-2.24.0.win32-py2.7 and RSVG 2.22.3-1_win32, in which I can't find the get_dimensions_sub() function mentioned in other answers.

1

There are 1 best solutions below

0
On

I've searched the web tonight trying to solve this seemingly simple problem. There does not seem to be a simple way of getting the bounding box of the drawing with rsvg, cairo or similar tools. Unless I'm missing something obvious.

However, you can call Inkscape with the --query-all option. This gives you the dimensions of all objects in an SVG file, and the full drawing as the first entry in the list.

import subprocess
output = subprocess.check_output(["inkscape", "--query-all", "myfile.svg"])
values = [line.split(',') for line in output.split('\n')]
whole_drawing = values[0]
[x, y, width, height] = map(float, whole_drawing[1:])

Now you'll have the drawing's position in x, y and its width and height. With this, it becomes simple to use rsvg and cairo to redraw the clipped SVG to a new file.

I created a simple tool to do this, I hope the code should be rather easy to understand.