Skip to content

Rendering an SVG with librsvg and Cairo

Brenden Matthews edited this page Jan 18, 2025 · 2 revisions

Below is a function that renders an SVG file using a combination of librsvg and Cairo. The Lua script is as follows:

require("cairo")
require("cairo_xlib")
require("rsvg")

function conky_draw_svg_file(path, x, y, w, h)
  if conky_window == nil then
    return
  end

  -- load svg
  local rh = rsvg_create_handle_from_file(path)

  -- create cairo surface
  local cs = cairo_xlib_surface_create(conky_window.display, conky_window.drawable, conky_window.visual, x + w, y + h)
  local cr = cairo_create(cs)

  -- translate
  cairo_translate(cr, x, y)

  -- create viewport
  local viewport = RsvgRectangle:create()
  viewport:set(x, y, w, h)

  -- render to cairo surface
  rsvg_handle_render_document(rh, cr, viewport)

  -- tidy up
  rsvg_destroy_handle(rh)
  viewport:destroy()
  cairo_destroy(cr)
  cairo_surface_destroy(cs)
end

To load the script, add the following to your Conky config, which would render the SVG at 0,0 with a width and height of 100 pixels:

conky.config = {
    -- ... existing config ...
    lua_load = "svg.lua",
    lua_draw_hook_pre = "conky_draw_svg_file /path/to/file.svg 0 0 100 100"
}
Clone this wiki locally