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

如何用flextable在RMarkdown生成的PDF/Word中实现横向表格?

解决flextable表格在PDF和Word中实现横向页面的方法

核心思路

PDF和Word的页面控制机制完全不同,需分输出格式针对性处理:

  • PDF:通过条件渲染插入LaTeX的\landscape/\endlandscape命令,避免在Word中输出无效代码
  • Word:借助officer包控制文档节的页面方向,实现表格所在页横向,后续自动恢复纵向

修改后的最小示例(MWE)

先安装并加载officer包,再替换原代码:

header-includes:
- \usepackage{pdflscape}
output:
  bookdown::pdf_document2:
    number_sections: false
    latex_engine: xelatex
  bookdown::word_document2: 
    number_sections: false
always_allow_html: true
geometry: "left=2.5cm,right=2cm,top=2cm,bottom=2cm"
fontsize: 12pt
linestretch: 1.5
---
```{r setup, include=FALSE}
library(knitr)
knitr::opts_chunk$set(echo = FALSE, warning = F, message = F)
library(dplyr)
library(flextable)
library(ftExtra)
library(officer) # 用于Word页面方向控制

Some text on portrait page

# 判断当前输出格式
is_pdf <- knitr::is_latex_output()
is_word <- knitr::is_word_output()

if (is_pdf) {
  # PDF输出:插入LaTeX横向环境起始命令
  cat("\\landscape")
} else if (is_word) {
  # Word输出:设置当前节为横向页面
  cat(officer::block_section(
    prop_section(
      page_size = page_size(orient = "landscape", width = 21, height = 29.7),
      type = "continuous"
    )
  ))
}

# 生成目标flextable表格
flextable(mtcars)%>%
  autofit()%>%
  theme_booktabs(bold_header = T)%>%
  set_caption("Table caption")%>%
  fontsize(size = 11, part =  "all")

if (is_pdf) {
  # PDF输出:结束LaTeX横向环境
  cat("\\endlandscape")
} else if (is_word) {
  # Word输出:恢复后续页面为纵向
  cat(officer::block_section(
    prop_section(
      page_size = page_size(orient = "portrait", width = 21, height = 29.7),
      type = "continuous"
    )
  ))
}

More text, next line back to portrait

### 关键说明
- **PDF处理**:通过`knitr::is_latex_output()`判断输出格式,仅在PDF模式下插入LaTeX横向命令,避免Word文档出现无效代码
- **Word处理**:用`officer::prop_section()`定义横向页面属性,`block_section()`将其插入文档;表格渲染完成后再插入纵向页面属性的节,确保后续内容回到纵向
- 代码块需设置`results='asis'`,让R输出的控制代码直接被渲染引擎解析

### 渲染命令保持不变
```r
bookdown::render_book(".", "bookdown::word_document2", config_file = "_bookdown.yml", preview = F, clean = T)
bookdown::render_book(".", "bookdown::pdf_document2", config_file = "_bookdown.yml", preview = F, clean = T)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 12:03:33