Plumber R Render a svg file

336 Views Asked by At

Im using plumber 1.0.0 to create an API GET and I want to render an svg with dynamic resolution

Reading the documentation we see that is possible change the resolution in a static way. But I need that the API calls this function with the parameters for resolution (to be responsive).

My last try was create the svg file and save as an temporary file, and then I want to "read" this saved svg file and return as output the graph saved as svg.

Anyone knows how to do this?

I try the same logic with png, and worked.

But when i try load the svg file, dont work properly...

Thanks!

1

There are 1 best solutions below

0
On BEST ANSWER

serializer_svg ultimatly calls grDevices::svg, it should tell you which options are available on the device. Normally they are set at parse time but you can dynamically override them with something like this ugly hack.

We make sure to set the requested value by using a filter that will be executed before the device is turned on.

library(plumber)

device_size <- function() {
  h_ <- 7
  w_ <- 7
  list(
    h = function() h_,
    w = function() w_,
    set_h = function(h) if (!is.null(h)) {h_ <<- as.numeric(h)},
    set_w = function(w) if (!is.null(w)) {w_ <<- as.numeric(w)}
  )
}

output_size <- device_size()

serializer_dynamic_svg <- function(..., type = "image/svg+xml") {
  serializer_device(
    type = type,
    dev_on = function(filename) {
      grDevices::svg(filename,
                     width = output_size$w(),
                     height = output_size$h())
    }
  )
}
register_serializer("svg", serializer_dynamic_svg)

#* @filter dynamic_size
function(req) {
  if (req$PATH_INFO == "/plot") {
    output_size$set_w(req$args$width)
    output_size$set_h(req$args$height)
  }
  plumber::forward()
}

#* @get /plot
#* @param width
#* @param height
#* @serializer svg
function() {
  plot(iris)
}