nblock's ~

Export multiple SVG layers

Images in presentations tend to be very similar to each other. For example a base image visualizes an empty sequence diagram and with each slide in the presentation more and more items are added to the sequence diagram (e.g. slides for my talk at Grazer Linuxtage 2017). Inkscape is a nice solution to draw such diagrams because it allows to put the various steps on different layers. Different images may be generated by selectively showing/hiding layers before running the export process.

Unfortunately, Inkscape (version <= 0.92) does not provide a command line option where the user can pass a list of layers that should be visible in the exported image. One can export such images by hand using the Inkscape GUI but this is an error prone and repetitive process and should be automated. Since SVG is just an XML file, one can use other XML tools to perform the desired processing before exporting.

Suppose you have an SVG file with the following layers (labels):

  • base
  • transport-1
  • transport-2
  • transport-3

In order to create a new SVG file where only the layers base and transport-1 are visible, the following command may be used:

$ xmlstarlet ed -P \
  -N inkscape=http://www.inkscape.org/namespaces/inkscape \
  -N svg=http://www.w3.org/2000/svg \
  -u '//*/svg:g[@inkscape:label]/@style' -v display:none \
  -u '//*/svg:g[@inkscape:label="base"]/@style' -v display:inline \
  -u '//*/svg:g[@inkscape:label="transport-1"]/@style' -v display:inline \
  input.svg > output.svg

The command above loads SVG namespaces, selects objects with by using an XPath expression and updates the display attribute to the desired value. The first step is to select all labels and hide them. After that, the labels base and transport-1 are selected to display them.

The resulting SVG file can be converted to another format such as PDF using Inkscape:

$ inkscape --without-gui --export-area-page --export-pdf-version="1.5" \
  --export-pdf=output.pdf output.svg

Hide this somewhere in a Makefile and you're done.


permalink

tagged inkskcape, svg and xmlstarlet