You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用rvg和officer导出PPT可编辑矢量图时字体填充异常求助

解决showtext配合rvg/officer导出PPT时字体填充异常的问题

问题根源

showtext的渲染机制是将文本转换为路径/位图,而非保留原生字体引用,这与rvg导出可编辑矢量图形的需求冲突,导致PPT中文字出现填充异常。而ggplot默认字体是系统原生字体,rvg可以正常识别处理。

修复方案

核心是让ggplot使用系统已安装的原生字体,而非依赖showtext的渲染层,具体步骤如下:

1. 确保目标字体(Poppins)已安装到系统

  • 若未安装,可通过以下方式获取并安装:
    library(showtext)
    font_add_google("Poppins")
    # 将字体导出到本地目录,之后手动安装到系统(不同系统安装方式不同)
    font_export("Poppins", output_dir = "./fonts")
    
  • 用gdtools::font_family_exists("Poppins")验证字体已成功安装到系统。

2. 不依赖showtext渲染图表,直接使用系统字体

library(ggplot2)
library(officer)
library(rvg)
library(gdtools)

# 验证字体存在
stopifnot(font_family_exists("Poppins"))

# 生成图表,直接指定系统字体
p <- ggplot(mtcars, aes(x = cyl)) + 
  geom_bar() +
  ggtitle("A B C D") +
  theme(text = element_text(family = "Poppins"))

# 导出为可编辑矢量PPT
pptx <- read_pptx()
pptx <- add_slide(pptx, layout = "Blank", master = "Office Theme")
pptx <- ph_with(
  x = pptx,
  value = dml(ggobj = p, fonts = list(sans = "Poppins")),
  location = ph_location(width = 6, height = 6)
)
print(pptx, target = "Slide_ABCD.pptx")

3. 若必须使用showtext(如临时加载字体),导出前关闭showtext自动渲染

如果已经用showtext加载了字体,需在导出前临时关闭其自动渲染,让ggplot调用系统字体:

library(ggplot2)
library(showtext)
library(officer)
library(rvg)

font_add_google("Poppins")
showtext_auto()

# 生成带自定义字体的图表
p <- ggplot(mtcars, aes(x = cyl)) + 
  geom_bar() +
  ggtitle("A B C D") +
  theme(text = element_text(family = "Poppins"))

# 导出前关闭showtext,切换到系统字体渲染
showtext_auto(FALSE)

# 导出PPT
pptx <- read_pptx()
pptx <- add_slide(pptx, layout = "Blank", master = "Office Theme")
pptx <- ph_with(
  x = pptx,
  value = dml(ggobj = p, fonts = list(sans = "Poppins")),
  location = ph_location(width = 6, height = 6)
)
print(pptx, target = "Slide_ABCD.pptx")

# 可选:恢复showtext自动渲染
showtext_auto(TRUE)

关键注意事项

  • 必须确保字体已安装到系统,仅通过font_add_google加载到showtext环境是不够的,rvg无法识别这种临时加载的字体。
  • dml的fonts参数需明确指定对应字体族,确保rvg能正确映射字体信息到PPT。

内容的提问来源于stack exchange,提问作者xilliam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 15:43:11