pdf和rmarkdown中的单词的分页符

时间:2018-11-15 11:00:59

标签: pdf ms-word r-markdown knitr page-break

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

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

我可以使用编辑>查找... 全部替换,但是由于我仍在开发报告,因此需要经常测试两者的输出看起来都不错格式。

有什么办法吗?

  • 在R函数中执行全部替换
  • 编辑tex模板,使第5部分不显示在pdf输出中(\ newpage在ms字中未显示),或者
  • 应用魔术命令强制分页符与所有格式兼容?

谢谢!

这是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.

1 个答案:

答案 0 :(得分:1)

非常感谢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和_document一起使用,随后在Word中直接添加目录非常容易。另外,上面的链接中有指向该问题的解决方案的链接。

相关问题