闪亮的应用程序运行代码生成pdf然后提供该pdf给用户下载

时间:2015-08-14 14:49:25

标签: r shiny

在我的闪亮应用程序中,我希望能够单击下载按钮,让它执行我在(在一个包中)在/ results文件夹中创建pdf的函数,然后将该创建的文件作为下载提供给闪亮的应用用户。我从下面的服务器粘贴了我当前的download_portfolio下载按钮代码(很多部分不确定如何使其可重现)。想知道是否有人知道什么是错误的,我收到下面的错误消息,但是FUNCTION_TO_GENERATE_PDF_IN_ / results()函数确实运行并创建了PDF,但随后应用程序重新加载,用户永远不会被提示下载。 / p>

我收到的错误(但我的功能仍然正确生成了pdf,只是应用程序重新加载,并且没有下载pdf的优惠)。

   Error in self$downloads$set(name, list(filename = filename, contentType = contentType,  : 
      argument "content" is missing, with no default

app.R代码,我正在处理下载

observe({
  output$download_portfolio <- downloadHandler({
    FUNCTION_TO_GENERATE_PDF_IN_/results()
    filename = function() { paste(input$pdfname) }
    content = function(file) {
      file.copy(paste("results/",input$pdfname, file, overwrite = TRUE)
    } 
  })
  })

1 个答案:

答案 0 :(得分:4)

您错误地使用了downloadHandler。你不需要observe() - 函数,因为有光泽提供"reactivity",这意味着你可以将对象绑定到ui元素,每当对象发生变化时都会更新。 因此,您只需要为下载按钮分配downloadHandler,并告诉它如何生成您要提供的文件:

library(shiny)

ui <- fluidPage( # just the download-button and a textInput for the filename
  textInput("pdfname", "Filename", "My.pdf"),
  downloadButton("outputButton", "Download PDF")
  )

server <- function(session, input, output) {
  # No need for an observer! Just assign the downloadHandler to the button.
  output$outputButton <- downloadHandler(input$pdfname, function(theFile) {
    # The first parameter is the name given to the file provided for download to the user.
    # The parameter in the function (theFile) is a placeholder for the name that is later
    # assigned to the download-file. 

    # Now you can call your pdf-generating function...
    makePdf()

    # ... and use file.copy to provide the file "in" the save-button
    file.copy(from = "/results/myGenerated.pdf", to = theFile)
  })
}

# Sample pdf-generating function:
makePdf <- function(){
  pdf(file = "/results/myGenerated.pdf")
  plot(cars)
  dev.off()
}

shinyApp(ui = ui, server = server)

但是,您不需要先存储文件,您可能希望直接保存它们&#34;在&#34;下载按钮:

library(shiny)

ui <- fluidPage( # As above
  textInput("pdfname", "Filename", "My.pdf"),
  downloadButton("outputButton", "Download PDF")
  )

server <- function(input, output) {
  output$outputButton <- downloadHandler(input$pdfname, function(theFile) {
    # Here, your pdf-generator is provided with the "filename" that is used
    # to provide the file for the user.
    makePdf(theFile)
  })
}

# Sample pdf-generating function:
makePdf <- function(filename){
  pdf(file = filename)
  plot(cars)
  dev.off()
}

shinyApp(ui = ui, server = server)