pdf - 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 函数中进行全部替换,
- 编辑 tex 模板以使第 5 节不显示在 pdf 输出中(\newpage in not shown in ms word),或
- 应用魔术命令强制分页符与所有格式兼容?
谢谢!
这是 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.
解决方案
非常感谢 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 中添加目录非常容易。另外,上面的链接中还有一个指向该问题的解决方案的链接。
推荐阅读
- c - 如何将 4 个无符号字符数组元素合并为一个十六进制值?
- jenkins - 如何获取 Jenkins 中所有宏的列表?
- python - 绘制具有重叠轮廓的每个 df 列的直方图
- azure - Azure AD B2C - 使用电子邮件或手机注册/登录
- node.js - 我应该如何在 NodeJS 中存储文件
- python - 为什么我在运行代码时可以看到 pip list sklearn 但在 Jupyter 中看不到?
- dialogflow-es - 如何格式化 DialogFlow 中 Facebook Messenger 响应的 @sys.date 和 @sys.time?
- java - 在 VS Code 中调试已编译的 Java .class 文件
- java - 在运行 Spring Boot 1.2.5 的嵌入式 Jetty 中禁用 TLS1
- html - 如何在移动设备上堆叠两个 div,但在桌面上并排排列?