Shiny app output can't be saved as pdf

I intend to export the shiny result to a pdf file and therefore used the following codes. But after after I hit the Download button in the application, the error is "the pdf file can't be opened because it has no pages". Would you please let me know what the problem is?

library(shiny)
library(gridExtra)
ui <- fluidPage(
  
  # App title ----
  titlePanel("Hello Shiny!"),
  
  sidebarLayout(
    
    
    sidebarPanel(
      
      
      sliderInput(inputId = "bins",
                  label = "Number of bins:",
                  min = 1,
                  max = 50,
                  value = 30), 
      downloadButton('export')
    ),
    
    # Main panel for displaying outputs ----
    mainPanel(
      
      
      plotOutput(outputId = "p1")
      
    )
  )
)



server <- function(input, output) {
  vals <- reactiveValues(p1=NULL)
  output$p1 <- renderPlot({
    
    x    <- faithful$waiting
    bins <- seq(min(x), max(x), length.out = input$bins + 1)
    
    vals$p1 <- hist(x, breaks = bins, col = "#75AADB", border = "white",
                    xlab = "Waiting time to next eruption (in mins)",
                    main = "Histogram of waiting times")
    vals$p1
  })
  output$export = downloadHandler(
    filename = function() {"plots.pdf"},
    content = function(file) {
      pdf(file, onefile = TRUE)
      vals$p1
      dev.off()
    }
  )
}
shinyApp(ui = ui, server = server)

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