问题
I am new to shiny and was wondering if there is a way to display a pdf file generated in "downloadHandler"?
I am using a package to do some biological analysis, and I can make it create a pdf file in downloadHandler. However, I am still struggling if I can view this pdf instead of downloading it.
This question is related to Shiny to output a function that generates a pdf file itself. Please see the below for the code that works for downloading the pdf output. Thanks so much!
library(shiny)
library(msa)
runApp(list(
#Load the exmaple from the msa package.
mySequenceFile <- system.file("examples", "exampleAA.fasta", package="msa"),
mySequences <- readAAStringSet(mySequenceFile),
myFirstAlignment <- msa(mySequences),
# A simple shiny app.
# Is it possible to see the generated pdf file on screen?
ui = fluidPage(downloadButton('downloadPDF')),
server = function(input, output) {
output$downloadPDF = downloadHandler(
filename = 'myreport.pdf',
content = function(file) {
msaPrettyPrint(
myFirstAlignment
, file = 'myreport.pdf'
, output="pdf"
, showNames="left"
, showLogo="top"
, consensusColor="BlueRed"
, logoColors="accessible area"
, askForOverwrite=FALSE)
file.rename("myreport.pdf", file) # move pdf to file for downloading
},
contentType = 'application/pdf'
)
}
))
回答1:
If you intend to display the pdf, you should not use downloadHandler
. Instead, just use your pdf printing function to generate the pdf file, but the key is
- Create a
www
folder under your Shiny project root - Point the file argument of
msaPrettyPrint
towww/myreport.pdf
- Dynamically add an iframe to display the file. Note in the iframe you point to
myreport.pdf
directly withoutwww
, as Shiny automatically looks for static/media files inside thewww
folder.
See below for a working example (note I am not using the msa package here but the idea should be the same).
library(shiny)
ui <- shinyUI(fluidPage(
titlePanel("Old Faithful Geyser Data"),
sidebarLayout(
sidebarPanel(
actionButton("generate", "Generate PDF")
),
mainPanel(
uiOutput("pdfview")
)
)
))
server <- shinyServer(function(input, output) {
observeEvent(input$generate, {
output$pdfview <- renderUI({
pdf("www/myreport.pdf")
hist(rnorm(100))
dev.off()
tags$iframe(style="height:600px; width:100%", src="myreport.pdf")
})
})
})
shinyApp(ui = ui, server = server)
来源:https://stackoverflow.com/questions/39580060/r-shiny-how-to-display-a-pdf-file-generated-in-downloadhandler