如何在Shiny应用程序中下载PDF文件 [英] How to download a PDF file in a Shiny app
问题描述
我的闪亮应用程序的www目录中有一个PDF。我希望该文件可以下载。我该怎么做。
I have one PDF in the www directory of my shiny app. I would like that file to be available for download. How can i do that.
下载示例效果很好,但不知道将其用于从www目录下载PDF。
The download example works well, but no idea to use it for PDF download from www directory.
## Only run examples in interactive R sessions
if (interactive()) {
ui <- fluidPage(
downloadLink("downloadData", "Download")
)
server <- function(input, output) {
# Our dataset
data <- mtcars
output$downloadData <- downloadHandler(
filename = function() {
paste("data-", Sys.Date(), ".csv", sep="")
},
content = function(file) {
write.csv(data, file)
}
)
}
shinyApp(ui, server)
}
推荐答案
查看 downloadHandler
函数文档,它有两个没有默认值的参数:文件名和内容。
Take a look in the downloadHandler
function documentation, it has two arguments without default values: filename and content.
文件名基本上是将要下载的文件的名称。它不必在函数内部。 filename = your-pdf-name.pdf
的作用与在无参数函数中定义它一样。
filename is basecaly 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 the most cases you're going to create a file that is going to be fulfilled with something your created in you app.
那不是您的情况,我的解决方案提供了在巴西我们称之为 gambiarra的东西:它将您要下载的文件复制到Shiny需要的临时文件中,以供 downloadHandler
工作。 (我尝试过将其定义为文件的路径,但它不起作用)
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)
这篇关于如何在Shiny应用程序中下载PDF文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!