Luca Sepe

How to convert sourcecode to PNG image

PNG Slides

Since I haven't found a direct way to convert sourcecode to PNG images yet, this is how I do it.

Step 1 - Convert sourcecode to SVG

To convert source code to SVG I use Highlight.

Highlight converts sourcecode to HTML, XHTML, RTF, ODT, LaTeX, TeX, 👉 SVG 👈, BBCode, Pango markup and terminal escape sequences with coloured syntax highlighting.

See my previous post about how to use Highlight.

highlight --font 'Fira Code' --font-size 24 \
          --out-format=svg \
          --style=print \
          --width 900 --height 380 \
          -i hello.go -o hello.svg

Step 2 - Convert the generated SVG to PNG

To turn SVG files into PNG images I use rsvg-convert.

This tool belongs to librsvg. A library to render SVG images to Cairo surfaces. GNOME uses this to render SVG icons.

rsvg-convert --keep-aspect-ratio \
             --width 400 --output hello.png hello.svg

How to install rsvg-convert

On Debian:

sudo apt-get install librsvg2-bin