firmo23
firmo23

Reputation: 8404

Getting error when trying to download pdf table from imported csv file in shiny app

Hi I have a simple shiny app from which i wish to download a pdf table after importing a csv file into it. I suspect that i use the parameters incorrectly as i take :

Error : 'file' must be a character string or connection

#ui.r
library(shiny)
library(rmarkdown)

fluidPage(sidebarLayout(
  sidebarPanel(
    fileInput("file1", "Input CSV-File"),
    downloadButton(
      outputId = "downloader",
      label = "Download PDF"
    )
  ),
  mainPanel(tableOutput("table"))
))
#server.r
function(input, output) {

  thedata <- reactive({
    inFile <- req(input$file1)
    read.csv(inFile$datapath)
  })
  output$table <- renderTable({
    thedata()
  })
  output$downloader <- downloadHandler(
    filename = "Student-report.pdf",
    content = function(file){
      out = rmarkdown::render("kable.Rmd")
      file.rename(out, file)
    }
  )
}
#kable.rmd
---

output: pdf_document
params:
  table: 'NULL'
  file: 'NULL'
---

```{r echo = FALSE, message = FALSE, include = FALSE}

library(knitr)
```

```{r nice-tab, tidy = FALSE, echo = FALSE, message = FALSE}
read.csv(file = params$file1)

```
```{r}
params[["table"]]
```

Upvotes: 0

Views: 371

Answers (1)

amrrs
amrrs

Reputation: 6325

The issue was with using file in your Rmd file. And because you've got the dataframe in a reactive function, you don't have to pass the file separately. Please see the updated code:

#ui.r
library(shiny)
library(rmarkdown)

ui <- fluidPage(sidebarLayout(
  sidebarPanel(
    fileInput("file1", "Input CSV-File"),
    downloadButton(
      outputId = "downloader",
      label = "Download PDF"
    )
  ),
  mainPanel(tableOutput("table"))
))
#server.r
server <- function(input, output) {

  thedata <- reactive({
    inFile <- req(input$file1)
    read.csv(inFile$datapath)
  })
  output$table <- renderTable({
    thedata()
  })
  output$downloader <- downloadHandler(
    filename = "Student-report.pdf",
    content = function(file){
      out <- rmarkdown::render("kable.Rmd", pdf_document())
      file.rename(out, file)
    }
  )
}

shinyApp(ui,server)

Kable.Rmd

---
output: pdf_document
---

```{r echo = FALSE, message = FALSE, include = FALSE}

library(knitr)
```


```{r}
kable(thedata())
```

Upvotes: 1

Related Questions