Trim LilyPond SVG Output

LilyPond is a music engraving program based on plain text. It produces beautiful note sheets like, e.g., the following:

The first measures of Bach’s Wohltemperiertes Clavier, set with LilyPond

(Source: Mutopia Project)

LilyPond supports SVG output natively:

lilypond -dbackend=svg sheet.ly
# will produce a file sheet.svg

However, the canvas of this file will be much larger than it needs to be. A quick postprocessing step using Inkscape’s command line interface can get rid of that excess space, though.

And while we’re at it, we’ll also throw in SVGO for good measure to minify the result at the same time:

ly_to_svg() {
BASE="$(basename "$1" .ly)"
lilypond --silent -dno-point-and-click -dbackend=svg --output=tmp1"$BASE" "$1"
inkscape -z --export-area-drawing --export-plain-svg=tmp2"$BASE".svg tmp1"$BASE".svg
svgo --quiet -o "$BASE.svg" tmp2"$BASE".svg
/bin/rm tmp?"$BASE".svg
}

ly_to_svg sheet.ly

The parameters explained:

  • lilypond -dno-point-and-click: This removes the links, that LilyPond automatically adds to the SVG, that link back to the .ly file. It’s a nice feature, but can be dangerous in production, since it may give away your local machine’s path layout. The LilyPond docs themselves suggest to switch it off.
  • lilypond -dbackend=svg: enables SVG output. The docs say, that lilypond --format=svg should work as well, but I wasn’t able to make that work.
  • inkscape -z: run in CLI mode, without graphical window.
  • inkscape --export-area-drawing: clip the image to only the visible parts.
  • inkscape --export-plain-svg=filename: export to an SVG file without Inkscape-specific extensions.

In the last line of the function, we remove all temporary files again with the Bash globbing character ?, that matches exactly one character.

The result is a perfectly cropped and minified file named sheet.svg.