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

痴心易碎 提交于 2019-12-11 16:11:55

问题


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"]]
```

回答1:


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())
```


来源:https://stackoverflow.com/questions/48779611/getting-error-when-trying-to-download-pdf-table-from-imported-csv-file-in-shiny

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!