Phil
Phil

Reputation: 8127

Name of downloadable file from Shiny app does not exactly match specification

I'm basing my code below on this page on R Studio on creating apps with downloadable reports. I've created the following app and .Rmd documents, which are both saved in the same directory:

app.R:

library(rmarkdown)
library(shiny)

shinyApp(
  ui = fluidPage(
    sliderInput("slider", "Slider", 1, 100, 50),
    downloadButton("report", "Generate report")
  ),
  server = function(input, output) {
    output$report <- downloadHandler(
      filename = "report.pdf",
      content = function(file) {
        tempReport <- file.path(tempdir(), "report.Rmd")
        file.copy("report.Rmd", tempReport, overwrite = TRUE)

        params <- list(n = input$slider)

        render(tempReport, output_file = file,
           params = params,
           envir = new.env(parent = globalenv())
        )
      }
    )
  }
)

report.Rmd:

---
title: "Dynamic report"
output: pdf_document
params:
  n: NA
---

```{r}
# The `params` object is available in the document.
params$n
```

A plot of `r params$n` random points.

```{r}
plot(rnorm(params$n), rnorm(params$n))
```

When I click on the "Generate report" button, the file that gets saved is called "report", when in fact I named it "report.pdf". I end up having to add ".pdf" manually into the filename in order for my computer to recognize it as a PDF document.

Is there a reason why the filename doesn't match exactly what I specified? What else am I supposed to do?

Upvotes: 2

Views: 387

Answers (1)

AEF
AEF

Reputation: 5670

Try to set the the contentType argument of downloadHandler to the correct MIME type, i.e. to "application/pdf".

Upvotes: 1

Related Questions