R语言formattable表格导出图片时修改全局字体家族方法咨询
解决方案
你需要在formattable的全局表格样式中指定字体家族,同时修正原代码中table.attr的语法错误(多余的转义符导致样式不生效),修改后可直接全局生效Calibri字体。
完整修改后代码
library("htmltools") library("webshot") library(formattable) DF <- data.frame(Ticker=c("", "", "", "IBM", "AAPL", "MSFT"), Name=c("Dow Jones", "S&P 500", "Technology", "IBM", "Apple", "Microsoft"), Value=accounting(c(15988.08, 1880.33, 50, 130.00, 97.05, 50.99)), Change=percent(c(-0.0239, -0.0216, 0.021, -0.0219, -0.0248, -0.0399))) unit.scale = function(x) (x - min(x)) / (max(x) - min(x)) export_formattable <- function(f, file, width = "100%", height = NULL, background = "white", delay = 0.2) { w <- as.htmlwidget(f, width = width, height = height) # 额外注入全局样式,双重保险确保字体生效 w <- htmlwidgets::prependContent(w, tags$style(" .formattable_widget * { font-family: Calibri, sans-serif !important; } ")) path <- html_print(w, background = background, viewer = NULL) url <- paste0("file:///", gsub("\\\\", "/", normalizePath(path))) webshot(url, file = file, selector = ".formattable_widget", delay = delay) } FT <- formattable(DF, list( Name=formatter("span", style = x ~ ifelse(x == "Technology", style(font.weight = "bold"), NA)), Value = color_bar("orange" , fun = unit.scale ), Change = formatter("span", style = x ~ style(color = ifelse(x < 0 , "red", "green"), "font.size" = "18px"), x ~ icontext(ifelse(x < 0, "arrow-down", "arrow-up"), x) )), # 修正样式语法,添加字体配置 table.attr = 'style="font-size: 18px; font-family: Calibri, sans-serif;"') FT export_formattable(FT,"FT.png")
改动说明
- 修正了原代码中
table.attr的错误转义符,新增font-family: Calibri配置,指定表格全局字体 - 在
export_formattable函数中额外注入了全局样式,用!important强制所有表格内元素继承Calibri字体,避免个别formatter自定义样式覆盖全局配置 - 同时修复了你注释中提到的「Technology行加粗不生效」的问题,该问题是原
table.attr语法错误导致所有全局样式失效导致的
注意事项
如果你使用的是MacOS或Linux系统,需要先安装Calibri字体,否则webshot依赖的phantomjs会自动fallback到系统默认字体:
- Linux系统可执行
sudo apt install ttf-mscorefonts-installer安装微软字体包 - MacOS可通过brew安装
cabextract后下载安装微软官方字体包
内容的提问来源于stack exchange,提问作者JK Lambert
相关产品推荐
相关产品推荐

