I have a script which uses rdkit to create svg drawings of chemical molecules. I will use them on a web server, therefore, the size of the figures does matter. The current output is a string containing the svg file. I know that I can use Inkscape to remove the white background and "resize page to drawing" which is exactly what I want. But as I am creating quiet a lot of figures I am looking for a way to resize the figures automatically. My experience with python modules for svg is very limited, therefore I am hoping someone can suggest a module which can apply the needed changes.
I know that I can simply remove the
<rect style='opacity:1.0;fill:#ffffff;stroke:none' width='2000' height='2000' x='0' y='0'> </rect>
part from the svg file to remove the white background, but I have no Idea how to implement the 'resize page to drawing' part.
Any help is highly appreciated.
Inkscape can perform various functions from the command line, including what you are asking for.
My search first led me here:
That is an extensive list of many 'verbs' or actions that Inkscape can do from the command line. There are some linked pages from there but realized that information could be found with Inkscape's command line help
From the command line inkscape --help
is very thorough.
The output from the link provided above is just a copy of this command:
inkscape --verb-list
.
From that list, what we are looking for is FitCanvasToDrawing
inkscape --verb=FitCanvasToDrawing --verb=FileSave --verb=FileClose --verb=FileQuit input.svg
The format for 'verbs' is --verb=VerbName and many different actions can be chained. After all verbs, you provide the filename that Inkscape is going to open/manipulate (unfortunately verbs CANNOT take arguments which would expand the scripting possibilities).
The last verb (FileQuit) in the example above is optional as if you are looping through many files doing this, it will probably be quicker to leave Inkscape open rather than restarting it every couple of seconds.
This last point brings up one of Inkscape's limitations and that is that the UI needs to be open to perform this action which might slow down this process for bigger batches but trivial for one-offs. The bug report for this can be found here and has been marked as a 'Wishlist' item.
Finally, you mention python, but this could be batched out with a shell script by providing a variable at the end instead of a static filename and running that script from the command line on all svg files in a folder like so script *.svg
but feel free to use the language you are most comfortable with.