如何在R中将flextable保存为png

how to save flextable as png in R

我已经遵循了 link 的建议:,但我似乎面临着一个不同的问题,因为这个解决方案对我不起作用。 vanilla.table () 函数生成一个不同于 flextable () 函数的对象。

我正在使用 flextable 因为它允许理想的格式化可能性

示例:

library(flextable)
library(rtable)

# The example below work.
myft <- vanilla.table(
   head(mtcars) )
myft
writeLines(as.html(myft), "MyFlexTable.html")

# The example below does not work.
myft <- regulartable(
  head(mtcars), 
  col_keys = c("am", "carb", "gear", "mpg", "drat" ))
myft
writeLines(as.html(myft), "MyFlexTable.html")

ps:我知道可以通过单击 "Export> Save as Image" 手动下载照片,但我需要对其进行编程

提前致谢!

要将 flextable 保存为 png,您首先需要将其保存为 html 文件,然后使用 Webshot 从 html 文件中获取 png。

library(flextable)
myft <- regulartable(
  head(mtcars), 
  col_keys = c("am", "carb", "gear", "mpg", "drat" ))

# create an Rmd file ----
library(rmarkdown)
rmd_name <- tempfile(fileext = ".Rmd")
cat("```{r echo=FALSE}\nmyft\n```", file = rmd_name)

# render as an html file ----
html_name <- tempfile(fileext = ".html")
render(rmd_name, output_format = "html_document", output_file = html_name )

# get a png from the html file with webshot ----
library(webshot)
webshot(html_name, zoom = 2, file = "regulartable.png", 
        selector = "body > div.container-fluid.main-container > div.tabwid > table")