Crop SVG drawing to canvas size in command line

command lineimage manipulationinkscapesvg

I have SVG images produced by PlantUML, which has some parts of drawing outside of canvas. It makes it difficult to use such images and I need to crop drawing to canvas size. As I produce UML diagrams with script anyways, it would be really efficient to perform a cropping there as well.

So far I've tried two things:
a) resize canvas to drawing with Inkscape

inkscape --verb=FitCanvasToDrawing --verb=FileSave --verb=FileClose *.svg

This works fine, but I need to crop drawing to canvas size and this operation seems to be unavailable.

b) resize with rsvg-convert

rsvg-convert image.svg -w 1870 -h 1195 -f svg -o image.svg

This does exactly croping to the desired size, but image size increases ~10 times as now there are some binary images embedded into SVG. This is not acceptable for me.

Best Answer

I found an inelegant way to do that using orion's proposal. Assuming $svg_file_name is a variable containing file path to an SVG image.

First we need image width and height

width=$(exiftool -ImageWidth $svg_file_name | sed "s/.*: //;s/pt//g")
height=$(exiftool -ImageHeight $svg_file_name | sed "s/.*: //;s/pt//g")

PlantUML produces the diagram as a single group (tag <g>), let's place rectangle of canvas size over that group

sed -i "s|</g>|</g><polygon fill=\"#FFFFFF\" points=\"0,0,0,$height,$width,$height,$width,0\" style=\"stroke: #000000; stroke-width: 1.0;\"/>|" $svg_file_name

Now open image with inkscape, select all and clip the group with the rectangle

inkscape --verb=EditSelectAll --verb=ObjectSetClipPath --verb=FileSave --verb=FileClose $svg_file_name

With the latest Inkscape one needs to quit Inkscape instead of closing the file

inkscape --verb=EditSelectAll --verb=ObjectSetClipPath --verb=FileSave --verb=FileQuit $svg_file_name