How to download a PDF file in a Shiny app

If the file is in the www folder then you simply have to provide a link to it in the UI

... (in UI)
  tags$a("Click here to get the PDF", href="your-pdf-name.pdf")
...

If the filename is not known at start time then use uiOutput/renderUI and set rv$filename to the filename when you generate it.

... (in UI)
  uiOutput("dlURL")
...


... (in server)
  rv <- reactiveValues(filename="")

  output$dlURL <- renderUI({
    tags$a("Click here to get the file", href=rv$filename)
  })
...

Take a look in the downloadHandler function documentation, it has two arguments without default values: filename and content.

filename is basically the name of the file that will be downloaded. It has not to be inside a function. filename = "your-pdf-name.pdf" works as much as defining it inside the argumentless function.

content, in the other hand, creates a tempfile with the content that is going to be downloaded. In most cases you're going to create a file that is going to be fulfilled with something you have created in you app.

How that is not your case, my solution provides something we call "gambiarra" in Brasil: it copies the file you want to download to the tempfile that shiny needs to the downloadHandler works. (I've tried just define it as the path to the file but it doesn't work)

ui <- fluidPage(
  downloadLink("downloadData", "Download")
)

server <- function(input, output) {

  output$downloadData <- downloadHandler(
    filename = "your-pdf-name.pdf",
    content = function(file) {
      file.copy("www/teste.pdf", file)
    }
  )
}

shinyApp(ui, server)

Tags:

Download

R

Shiny