C.3 Querying

The textual nature of SVG makes it very easy to generate and edit SVG documents with simple scripts. However, no matter what your script is supposed to do, chances are that you will find it necessary to figure out the bounding boxes of some SVG objects (for example, to check if the text inserted into SVG from a database fits the provided space, or to create a background rectangle or frame for a specific object). Proper calculation of a bounding box, in a general case, is way too complex to do in a script—you would have to reimplement a lot of Inkscape’s geometry and rendering code if you want to take into account everything that may affect the bounding box.

Fortunately, instead of all that you can simply ask Inkscape. For example:

$ inkscape --query-width --query-id=text1256 file.svg
45.2916

Here, we asked Inkscape to tell us the width (in px units) of the object with the id="text1256". It loaded the document, found that object, printed its width back to the console, and then quit.

Similarly, you can --query-height, --query-x, and --query-y to find out the dimensions and coordinates of the object’s bounding box. Such Inkscape calls are reasonably fast because they don’t load the GUI and don’t render the document; however, if you need to query the bounding boxes of many objects, this may add up to quite a delay. In this case, it is better to use the --query-all parameter which returns all bounding box numbers for all objects in a document, as follows:

$ inkscape --query-all file.svg
svg2,-55.11053,-29.90404,328.3131,608.6359
layer1,-55.11053,-29.90404,328.3131,608.6359
image2372,-8.917463,349.8089,282.12,212.6382
text2317,-39.85518,454.3014,20.40604,13.32647
tspan2319,-32.58402,454.3014,12.79618,4.989286
tspan2408,-39.85518,462.4921,20.40604,5.135838
path2406,-16.43702,386.617,6.34172,154.7896
text2410,-46.11609,376.8753,34.34841,5.135838
tspan2414,-46.11609,376.8753,34.34841,5.135838
text2418,-55.11053,365.9197,43.02429,5.135838

Here, each line is a comma-separated list of: object ID, x, y, width, and height. Parsing such a line in your script should be easy.