Using downloadHandler and R Studio 'Export as pdf' (cairo_pdf)

I'm not sure why this is the case, but it works for me if the content function is included inline, instead of defined separately:

library(shiny)
library(Cairo)
library(grDevices)

ui <- fluidPage(
  
  mainPanel(
    tabsetPanel(
      tabPanel(
        "NMS Ordination", 
        textInput("dataset", "Data Set", value = "my_awesome_data"),
        plotOutput("ordplot"),
        downloadLink("downloadPlot", "Download Plot")
      )
    )
  )
)


server <- function(input, output, session){
  
  options(shiny.usecairo=T)
  
  output$ordplot <- renderPlot({
    plot(faithful)
  })
  
  output$downloadPlot <- downloadHandler(
    filename = function(){paste(input$dataset, '.pdf', sep = '')},

    content = function(file){
      cairo_pdf(filename = file,
                width = 18, height = 10, pointsize = 12, family = "sans", bg = "transparent",
                antialias = "subpixel",fallback_resolution = 300)
      plot(faithful)
      dev.off()
    },
    
    contentType = "application/pdf"
  )
}

shinyApp(ui=ui, server=server)

(I removed dev.copy2pdf(file) since I wasn't sure what it was supposed to do, given that cairo_pdf() is already creating a PDF file)

4 Likes