【问题标题】:Download and display PDF in Shiny在 Shiny 中下载并显示 PDF
【发布时间】:2017-05-02 21:44:50
【问题描述】:

我正在尝试在 shinyapps.io 上的应用程序中展示来自网络的一些 PDF。不幸的是,使用带有 URL 的 iframe 的标准方式不是一种选择,因为混合内容的保护措施(pdf 是通过 http 提供的)。我认为一个可能的选择是从 url 下载 pdf,然后在本地文件的 iframe 中显示它们,但我无法让它与 tempfile() 一起使用。

一个示例应用:

ui <- fluidPage(
  sidebarLayout(
      sidebarPanel(
        textInput("url", "add a url"),
        actionButton("button","hit the button"),
        h5("use case - embed a pdf user guide in the app - embed as a local pdf or from web URL")
      ), 
      mainPanel(
        tabsetPanel(
          tabPanel("PDF", 
                   htmlOutput("pdf")
                   )
          )
        )
      )
)

server <- function(input, output, session) {

  observeEvent(input$button, {
    temp <- tempfile(fileext = ".pdf")
    download.file(input$url, temp)

    output$pdf <- renderUI({
      tags$iframe(src=temp)
    })
  })
}

shinyApp(ui, server)

示例 pdf:http://www.pdf995.com/samples/pdf.pdf

当我在浏览器中打开它时,我在浏览器控制台中收到错误消息: Not allowed to load local resource: file:///C:/Users/.../Local/Temp/Rtmp8subWX/file19403a2a2fc8.pdf 并且 iframe 所在的面板中没有任何内容。

上传到 shinyapps.io 的类似尝试也失败了,在 pdf 查看器中显示 404 Not Found 错误。

我认为这可能是 shiny/shinyapps.io 如何处理临时文件的问题,但无法完全弄清楚。谢谢。

【问题讨论】:

    标签: r shiny


    【解决方案1】:

    您需要以二进制模式将 PDF 下载到当前目录的子文件夹中,然后调用 addResourcePath 以允许闪亮提供它:

      observeEvent(input$button, {
        pdf_folder <- "pdf_folder"
        if(!file.exists(pdf_folder))
          dir.create("pdf_folder")
        temp <- tempfile(fileext = ".pdf", tmpdir = "pdf_folder")
        download.file(input$url, temp, mode = "wb")
        addResourcePath("pdf_folder",pdf_folder)
    
        output$pdf <- renderUI({
          tags$iframe(src=temp)
        })
      })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-23
      • 1970-01-01
      • 2023-03-26
      • 2023-03-17
      • 2019-10-15
      • 2016-05-23
      • 2021-07-06
      相关资源
      最近更新 更多