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

如何在R的Quarto书籍PDF输出中实现正文双间距、表格单间距?

解决Quarto书籍PDF正文双间距、表格单间距的需求

问题背景

使用Quarto创建基于scrbook文档类的PDF书籍,全局设置linestretch: 2实现正文双间距后,表格也变成了双间距。尝试在生成表格的R代码块中设置linestretch: 1无效,需要实现正文双间距、表格单间距的效果。

可行解决方案

代码块的linestretch参数仅控制代码块自身的行距,无法作用于生成的表格。可以通过以下几种方法实现需求:

方法1:通过kable直接设置表格行距

利用LaTeX的arraystretch参数调整表格行距,由于全局linestretch=2,将表格的arraystretch设为0.5即可抵消全局双间距,实现单间距:

#| echo: false
#| label: tbl-cars
#| tbl-cap: "Details of Cars"
head(mtcars) |> 
  knitr::kable(
    format = "latex", 
    booktabs = TRUE,
    format.args = list(arraystretch = 0.5)
  )

方法2:用LaTeX环境包裹表格

在表格代码块前后添加LaTeX的单间距环境,手动切换行距:

\begin{singlespace}
#| echo: false
#| label: tbl-cars
#| tbl-cap: "Details of Cars"
head(mtcars) |> knitr::kable()
\end{singlespace}

方法3:全局修改表格环境(一次性生效所有表格)

创建自定义LaTeX模板,自动为所有表格设置单间距:

  1. 在项目根目录创建template.tex文件,添加以下内容:
\documentclass[$for(classoption)$$classoption$$sep$,$endfor$]{$documentclass$}

% 全局设置表格为单间距
\AtBeginEnvironment{tabular}{\renewcommand{\arraystretch}{0.5}}

$if(title)$
\title{$title$}
$endif$
$if(author)$
\author{$for(author)$$author$$sep$ \and $endfor$}
$endif$
$if(date)$
\date{$date$}
$endif$

$for(header-includes)$
$header-includes$
$endfor$

$if(subparagraph)$
\setcounter{secnumdepth}{5}
$else$
\setcounter{secnumdepth}{4}
$endif$

$if(linestretch)$
\usepackage{setspace}
\setstretch{$linestretch$}
$endif$

\begin{document}

$if(title)$
\maketitle
$endif$

$if(abstract)$
\begin{abstract}
$abstract$
\end{abstract}
$endif$

$for(include-before)$
$include-before$
$endfor$

$body$

$for(include-after)$
$include-after$
$endfor$

\end{document}
  1. 修改_quarto.yml的PDF格式配置,指定模板:
format:
  pdf:
    number-sections: true
    number-depth: 3
    documentclass: scrbook
    pdf-engine: lualatex
    geometry:
      - top=1in
      - bottom=1in
      - left=1in
      - right=1in
      - heightrounded
    linestretch: 2
    keep-md: true
    keep-tex: true
    template: template.tex  # 添加这一行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 16:43:40