使用函数将图像添加到 flextable

Adding image to flextable using function

我正在使用 Officer 创建一个很大的 Word 文档 table。我想在此 table 中插入一些图像。为此,我使用 flextable。以下代码将图像插入 flextable.

pupil.tbl <- tribble(
  ~col1, ~col2,
  paste("Name:", pupil$name), paste("Class:", pupil.class),
  "attendance_graph", "boxall_graph"
) 
# add attendance plot
pupil.ft <- flextable(as.data.frame(pupil.tbl))
pupil.ft <- display(
  pupil.ft, i=2, col_key = "col1", pattern = "{{att_tbl}}",
  formatters = list(
    att_tbl ~ as_image(
                 col1, 
                 src = "attendance.png", 
                 width = 3.3, 
                 height = 1.65)
               )
  )
)

这很好用,但我有很多图像要添加,所以我想我会把它抽象成一个函数。但是,当我尝试这样做时,我得到:

Error in data.frame(image_src = src, width = width, height = height, stringsAsFactors = FALSE) : object 'image_file' not found

这是函数和对函数的调用(目前它对除图像路径之外的所有内容使用全局变量)

pupil.ft <- add_img_to_flextable("attendance.png")

add_img_to_flextable <- function(image_file){
  return(
    display(
      pupil.ft, i=2, col_key = "col2", pattern = "{{att_tbl}}",
      formatters = list(
        att_tbl ~ as_image(
                    col1, 
                    src = image_file, 
                    width = 3.3,  
                    height = 1.65)
      )
    )
  )
}

如果您将 src 添加到输入 data.frame 的列中,它应该会按预期工作。我无法复制所有内容,因为我没有您的数据和图像。

library(flextable)
library(tibble)
download.file("https://www.r-project.org/logo/Rlogo.png", destfile = "Rlogo.png")
pupil.tbl <- tribble(
  ~col1, ~col2, ~col3,
  "A", "B", "Rlogo.png",
  "C", "D", "Rlogo.png"
) 
pupil.tbl <- as.data.frame(pupil.tbl)

# display only col1 and col2
pupil.ft <- flextable(pupil.tbl, col_keys = c("col1", "col2") )

add_img_to_flextable <- function(ft, i, j){
  display(
    ft, i=i, col_key = j, pattern = "{{att_tbl}}",
    formatters = list(# use col3 even if not displayed
      att_tbl ~ as_image(col3, src = col3, width = 1.29, height = 1)
    )
  )
}

pupil.ft <- add_img_to_flextable(pupil.ft, i = 2, j = "col2")
pupil.ft

请注意,我对display功能不满意,我可以看到它的用法太复杂了,我可能会在以后改进这一点。