使用 shiny 和 officer 包将 gt table 图像添加到 word 文档

add gt table image to word doc with shiny and officer package

我正在编写一个闪亮的应用程序:

我在创建图像时遇到困难....感谢任何帮助...这是我的代表

library(shiny)
library(gt)
library(dplyr)

ui <- fluidPage(
      
      
      downloadButton("report", "Generate Report")
      
      
)



server <- function(input, output, session) {
      
      
      my_table <- render_gt(
                
                mtcars[1:5,1:5] %>%
                          gt()
      )
      
      my_image <-reactive({
                
                outfile <- tempfile(fileext='.png')
                
                gtsave(my_table, outfile, width = 400, height = 300)
                
                
                
      })
      
      
      
      output$report <- downloadHandler(
                
                filename = function() {
                          "download.docx"
                },
                
                content = function(file) {
                          
                          
                          print(read_docx() %>%
                                          body_add_img(my_image()),
                                target = file)
                          
                          
                },
                contentType = "docx"
                
                
      )
      
      
      
}

shinyApp(ui, server)

您的代码存在几个问题:

  1. 您使用 render_gt 而不是 reactive
  2. 您的 reactive my_image 没有 return 添加到 docx 所需的临时文件的名称。此外,由于 my_table 是或应该是 reactive 使用 my_table()
  3. gtsave 中使用 vwidthvheight。参见 ?webshot::webshot
  4. In officer::body_add_img 你必须在 inches.
  5. 中设置 widthheight

可重现代码:

library(shiny)
library(gt)
library(dplyr)
library(officer)

ui <- fluidPage(
  downloadButton("report", "Generate Report")
)

server <- function(input, output, session) {
  my_table <- reactive({
    mtcars[1:5, 1:5] %>%
      gt()  
  })
  
  my_image <- reactive({
    outfile <- tempfile(fileext = ".png")
    gtsave(my_table(), outfile, vwidth = 400, vheight = 300)
    outfile
  })

  output$report <- downloadHandler(
    filename = function() {
      "download.docx"
    },
    content = function(file) {
      read_docx() %>%
        body_add_img(my_image(), width = 4, height = 3) %>%
        print(target = file)
    },
    contentType = "docx"
  )
}

shinyApp(ui, server)