Export plots to PDF from reactive/observeEvent

I have below renderPlot inside observeEvent as i am dynamically plotting (histogram + boxplot) based on dynamic user selection of tests. Everything is working fine. What I need now is to be able to save whatever plots rendered & save into PDF. I tried to basically copy the whole codes inside the renderPlot into downloadHandler (with pdf(file) & dev.off() blanketing the codes) but it is not working & I am getting below error:

Warning: Error in if: argument is of length zero
[No stack trace available]

pdf file was created but 0 byte (so nothing saved).

    output[[plotname]]<- renderPlot({
      req(input$param) #aes string input for single plot

      mybin <- input$bin
      col = as.name(input$param[my_i]) #take the next parameters from the list
      datcol <- as.data.frame(myval()[input$param])
      lims  <- as.data.frame(lims()[input$param])
      ll    <- lims[1,my_i]
      hl    <- lims[2,my_i]
      ave   <- round(mean(datcol[[my_i]]), digits = 4)

      histop <- hist(my_i, mybin, col, datcol, lims, ll, hl, ave)

      boxp   <- bp(my_i, mybin, col, datcol, lims, ll, hl)
      chart_align(histop, boxp)

I'd recommend starting by creating a reprex so that other people can actually help you. You can read some advice on that in https://mastering-shiny.org/action-workflow.html#getting-help.

Hi @hadley,

Thank you for the reply.
Basically, the blocker i am facing now is getting the plots into the PDF document.
Below is my downloadHandler codes which is not working.
But if I just replace the print line with like plot(x=my_n, y=my_n), the PDF export works.

    output$pdfDL <- downloadHandler(
      filename = "pplots.pdf",
      content <- function(file) {
        pdf(file, width = 10, height = 7)
        mp= length(myPlot)
         for (n in 1:mp) {   
            my_n <- n

As I said above, if you want to get help, you need to make it easier for people by providing a reprex. There is no way to tell what's going wrong with your code because there's no way to run it.

This topic was automatically closed 54 days after the last reply. New replies are no longer allowed.