首页 > 解决方案 > 尝试在 Shiny App 中使用 RMarkdown 下载 PDF

问题描述

我正在尝试从 Shiny App 中生成 PDF 格式的报告。我有两个问题:

  1. 报告没有以 PDF 格式下载,仅以 HTML 格式下载。我如何下载它的PDF?
  2. 报告未显示渲染的内容(在本例中为 ggplotly 图像),仅显示文本。如何使该 PDF 包含 Shiny App 中显示的图像?

我究竟做错了什么?有任何想法吗?

library(ggplot2)
library(plotly)
library(gapminder)
library(shiny)
library(shinydashboard)
library(rmarkdown)

bodyplotly <- dashboardBody(
  fluidRow(
    column(12,
           box(width=10,
               title = "ggplotly", 
               plotlyOutput("selected_plot"),
               box(
                 width = 2, height=250,
                 sliderInput("year", label=("Choose year"),
                             min = 1950, max = 2000, value = 1977),
                 downloadButton("report", "Generate report")
           )))))  
  
ui <- navbarPage("Test",tabPanel("plotly",
                          bodyplotly))

server <- function(input, output,session) {
  
  output$selected_plot <- renderPlotly({
    
    p <- gapminder %>%
      filter(year==input$year) %>%
      ggplot( aes(gdpPercap, lifeExp, size = pop, color=continent)) +
      geom_point() +
      theme_bw()
    
    ggplotly(p)
    
    
  })
  
  output$downloadreport <- downloadHandler(
    # For PDF output, change this to "report.pdf"
    filename = "report.html",
    content = function(file) {
      # Copy the report file to a temporary directory before processing it, in
      # case we don't have write permissions to the current working dir (which
      # can happen when deployed).
      tempReport <- file.path(tempdir(), "report.Rmd")
      file.copy("report.Rmd", tempReport, overwrite = TRUE)
      library(rmarkdown)
      # Set up parameters to pass to Rmd document
      params <- list(input$year)
      # Knit the document, passing in the `params` list, and eval it in a
      # child of the global environment (this isolates the code in the document
      # from the code in this app).
      rmarkdown::render(tempReport, pdf_document(),
                        #output_options=self_contained,
                        #params = params,
                        envir = new.env(parent = globalenv())
      )
    
    }
  )
  
  }
  
  shinyApp(ui = ui, server = server)

标签: rshinyr-markdownshinydashboardggplotly

解决方案


推荐阅读