首页 > 解决方案 > rmarkdown中pdf和word的分页符

问题描述

我正在尝试为我的数据分析开发一个 rmarkdown 报告,该报告可以在 word_document 和 pdf_document 中编写。Bookdown 非常适合字幕和自动编号(https://bookdown.org/yihui/bookdown/)。剩下的唯一主要问题是如何进行对两者都有效的分页符。

对于 pdf,我使用来自 tinytex 的 xelatex 并且\newpage效果很好。对于 Word,我使用第 5 节分页符并自定义样式(包括分页符和白色字体)。

我可以使用Edit > Find...Replace All,但由于我仍在开发报告并且需要经常测试两种格式的输出看起来都很好。

有什么办法可以:

谢谢!

这是 R Markdown 文件的复制示例:

---
title: "Untitled"
author: "Me"
date: "November 15, 2018"
output:
  pdf_document: default
  word_document: default
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
Some text.  

I want a page break after this.

\newpage
##### page break

This should be the first sentence of the new page.

Some more text.

标签: pdfms-wordr-markdownknitrpage-break

解决方案


非常感谢 tarleb 的回答。正如建议的那样,我使用了您对这篇文章的回答:https ://stackoverflow.com/a/52131435/2425163 。

步骤1:使用以下代码创建一个txt文件:

--- Return a block element causing a page break in the given format.
local function newpage(format)
  if format == 'docx' then
    local pagebreak = '<w:p><w:r><w:br w:type="page"/></w:r></w:p>'
    return pandoc.RawBlock('openxml', pagebreak)
  elseif format:match 'html.*' then
    return pandoc.RawBlock('html', '<div style=""></div>')
  elseif format:match '(la)?tex' then
    return pandoc.RawBlock('tex', '\\newpage{}')
  elseif format:match 'epub' then
    local pagebreak = '<p style="page-break-after: always;"> </p>'
    return pandoc.RawBlock('html', pagebreak)
  else
    -- fall back to insert a form feed character
    return pandoc.Para{pandoc.Str '\f'}
  end
end

-- Filter function called on each RawBlock element.
function RawBlock (el)
  -- check that the block is TeX or LaTeX and contains only \newpage or
  -- \newpage{} if el.format:match '(la)?tex' and content:match
  -- '\\newpage(%{%})?' then
  if el.text:match '\\newpage' then
    -- use format-specific pagebreak marker. FORMAT is set by pandoc to
    -- the targeted output format.
    return newpage(FORMAT)
  end
  -- otherwise, leave the block unchanged
  return nil
end

第 2 步:将文件另存为 page-break.lua 与我的 R Markdown 文件位于同一目录中。

第 3 步:将链接添加为 pandoc 参数。

这是可重现的示例(R Markdown 文件)更正:

---
title: "Untitled"
author: "Me"
date: "November 15, 2018"
output:
  pdf_document: default
  word_document:
    pandoc_args:
     '--lua-filter=page-break.lua'
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

Some text.  

I want a page break after this.

\newpage

This should be the first sentence of the new page.

Some more text.

请注意,这可能不适用于 toc,但我不会将 lua 过滤器与 pdf 和 word _document 一起使用,之后直接在 Word 中添加目录非常容易。另外,上面的链接中还有一个指向该问题的解决方案的链接。


推荐阅读