R Shiny how to display a pdf file generated in “downloadHandler”

梦想的初衷 提交于 2021-02-19 07:37:59

问题


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

  1. Create a www folder under your Shiny project root
  2. Point the file argument of msaPrettyPrint to www/myreport.pdf
  3. Dynamically add an iframe to display the file. Note in the iframe you point to myreport.pdf directly without www, as Shiny automatically looks for static/media files inside the www 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

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