1

Suppose we are given an SVG file, say canvas1.svg. In my case, this file will have been produced from a single-page PDF using pdf2svg.

I would like to have a bash script (let's call it 'svgbb.sh') that takes the filename of the SVG file as argument and returns as output the bounding box of the entire content of the SVG file, e.g. x1, y1, x2, y2, where (x1, y1) are the coordinates of the upper-left corner of the bounding box, and (x2, y2) are the coordinates of the lower-right corner of the bounding box.

Moreover, I would like the solution to be reasonably fast.

I know how to do it using Inkscape. Unfortunately, the resulting script is relatively slow to execute.

#!/bin/bash
filename="$1"

# In Inkscape, the bounding box of all objects is called the *drawing*. 
# The coordinates of the drawing can be obtained by invoking inkscape on 
# the command line with the options `-X`, `-Y`, `-W`, and `-H` (which are 
# the abbreviations for `--query-x`, `--query-y`, `--query-width`, and 
# `--query-height`)
# They can be all invoked at once. 
# Inkscape will return four numbers, in the units of px (normally 96 px=1 inch)

# capture the output of the inkscape invocation and store it in an array
a=(`inkscape -X -Y -W -H $filename`)

x1=${a[0]}
y1=${a[1]}
w=${a[2]}
h=${a[3]}

# now we perform some simple arithmetic using the 'bc' tool
x2=`echo $x1+$w | bc`
y2=`echo $y1+$h | bc`

# print the result
echo $x1 $y1 $x2 $y2

Again, this works, but is fairly slow.

Therefore, I'm looking for faster alternatives, which don't require the overhead of Inkscape. The script can use whatever free and easily obtainable tools are most appropriate: JavaScript (probably using Node.js, but maybe not), python, C (or C++, or…), etc., as long as it's noticeably faster than the solution with Inkscape I gave above.

I'm sure this JavaScript-based answer could be adapted, but I have almost no experience with JavaScript, so doing that on my own would require quite a bit of time investment.

0 Answers0