I would like to extract the bounding box of a SVG drawing.
Since Python is already available on the system and also used to perform other tasks, I don't want to use JavaScript or any other language. My understanding is if the bounding box of a single element can be calculated (but I don't know how).
The bounding box of the whole drawing is just the minimum and maximum x,y values a of all elements, hence probably the bounding boxes of all elements need to be calculated.
I am a Python beginner, but svgwrite
is probably not the right module and so far I was scared by the installation of rsvg
on a Windows system.
There may be a more direct approach to achieve this, but something like this should meet your requirements.
You can convert your file to a list of path objects with the svg2paths
method and iterate through them.
from svgpathtools import svg2paths
def get_bbox(svg_file):
paths, _ = svg2paths(svg_file)
for i, path in enumerate(paths):
if i == 0:
# Initialise the overall min-max with the first path
xmin, xmax, ymin, ymax = path.bbox()
else:
# Expand bounds to match path bounds if needed
p_xmin, p_xmax, p_ymin, p_ymax = path.bbox()
xmin = min(xmin, p_xmin)
xmax = max(xmax, p_xmax)
ymin = min(ymin, p_ymin)
ymax = max(ymax, p_ymax)
print(xmin, xmax, ymin, ymax)
get_bbox("myfile.svg")