首页 > 解决方案 > RMarkdown - 使用kable或huxtable的表格中的不同字体类型,输出到pdf?

问题描述

使用 huxtable,为不同的单元格/行输出不同字体的 html 是一件轻而易举的事。没有那么多的pdf。这并不是一个真正的新问题,而是一个特定版本的 RMarkdown - 使用 kable 的表格中的不同字体类型?更改 Rmarkdown pdf 中 Kable 的字体

我已使用https://stackoverflow.com/a/54735453/4927395给出的答案 从 rmarkdown (在我的 Windows 电脑上)创建下图中的输出。请注意,“环境”代码将更改表格(整个表格)的字体,但块之后的文本采用为表格指定的字体。建议解决这个问题?此外,我无法让浮动示例在我的计算机上运行,​​这就是它被注释掉的原因。我喜欢 huxtable,但还没有看到为表格选择的字体(与主字体不同)在网络上工作的示例。如果绝对必要,可以探索其他餐桌套餐。

    ---
title: "Reprex selecting font for kable table output to pdf"
output: 
  pdf_document:
    latex_engine: xelatex
header-includes:
  \usepackage{fontspec}
  \setmainfont[Path=C:/windows/fonts/]{SHOWG.TTF}
  \newfontfamily\arialfont[Path=c:/windows/fonts/]{ARIAL}
  \newenvironment{ctable}{\arialfont }{}
  \newenvironment{capctable}[1][t]{\begin{table}[#1]\centering\arialfont}{\end{table}}
---

here is some text

```{r}
library(knitr)
library(kableExtra)
#This works, though leaves the selected font active for text after the chunk
kable(head(mtcars), booktabs=TRUE, align = "c") %>% 
   kable_styling(table.envir="ctable", font_size=12) %>%
   row_spec(0, bold = T, color = "white", background = "gray")
#This next bit doesn't work
#kable(head(mtcars), booktabs=TRUE, align = "c", 
#       caption = "This table floats", table.envir = "capctable") %>% 
#   kable_styling(font_size=12) %>%
#   row_spec(0, bold = T, color = "white", background = "gray")
```


here is some more text

输出

标签: fontsr-markdownkablekableextra

解决方案


事实上,这里是如何在 huxtable 中执行此操作(我是包所有者)。您需要安装 xelatex 和 LaTeX“fontspec”包。您还需要 huxtable 4.4.0 或更高版本,目前在 github 上可用:

install_github("hughjonesd/huxtable")

在您的 rmarkdown 标头中:

output:
   pdf_document:
     latex_engine: xelatex

在 R 代码块中:

library(dplyr)
library(huxtable)
options(huxtable.latex_use_fontspec = TRUE)

mtcars %>%
      head() %>%
      as_huxtable() %>% 
      set_font("Times New Roman")


推荐阅读