【问题标题】:add gt table image to word doc with shiny and officer package使用闪亮和官员包将 gt 表图像添加到 word doc
【发布时间】:2022-01-21 02:30:52
【问题描述】:

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

  • 创建一个 gt 表
  • 将 gt 表保存为图像(临时文件)
  • 使用 {officer} 包将该图像传递到 word 文档中

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

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)

【问题讨论】:

    标签: r shiny officer gt


    【解决方案1】:

    您的代码有几个问题:

    1. 您使用render_gt 而不是reactive
    2. 您的reactive my_image 不返回将其添加到 docx 所需的临时文件的名称。此外,my_table 是或应该是 reactive 使用 my_table()
    3. gtsave 中使用vwidthvheight。见?webshot::webshot
    4. officer::body_add_img 中,您必须以英寸 为单位设置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)
    

    【讨论】:

    • 效果很好,学到了很多
    猜你喜欢
    • 1970-01-01
    • 2021-01-20
    • 1970-01-01
    • 2015-06-15
    • 2017-12-04
    • 2019-03-05
    • 1970-01-01
    • 1970-01-01
    • 2018-11-28
    相关资源
    最近更新 更多