首页 > 解决方案 > 如何在R中将flextable保存为png

问题描述

我已经遵循了链接的建议:R save FlexTable as html file in script,但似乎我面临一个不同的问题,因为这个解决方案对我不起作用。该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:我知道可以通过单击“导出>另存为图像”手动下载照片,但是我需要对其进行编程

提前致谢!

标签: rpngviewerflextable

解决方案


要将 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")

在此处输入图像描述


推荐阅读