How to add a page break in word document generated

2019-01-11 09:36发布

I writing a Word document with R markdown in R Studio. I can get many things, but at the moment I am not figuring out how can I get a page break. I have found solutions but only for rendered latex / pdf document that it is not my case.

9条回答
神经病院院长
2楼-- · 2019-01-11 10:12

Here is an R script that can be used as a pandoc filter to replace LaTeX breaks (\pagebreak) with word breaks, per @JAllen's answer above. With this you don't need to compile a pandoc script. Since you are working in R Markdown I assume one has R available in the system.

#!/usr/bin/env Rscript

json_in <- file('stdin', 'r')
lat_newp <- '{"t":"RawBlock","c":["latex","\\\\newpage"]}'
doc_newp <- '{"t":"RawBlock","c":["openxml","<w:p><w:r><w:br w:type=\\"page\\"/></w:r></w:p>"]}'
ast <- paste(readLines(json_in, warn=FALSE), collapse="\n")
ast <- gsub(lat_newp, doc_newp, ast, fixed=TRUE)
write(ast, "")

Save this as page-break-filter.R or something like that and make it executable by running chmod +x page-break-filter.R in the terminal.

Then include this filter the R Markdown YAML like so:

---
title: "Title
author: "Author"
output:  
  word_document:
    pandoc_args: [
      "--filter", "/path/to/pandoc-newpage-filter.R"
    ]
---
查看更多
3楼-- · 2019-01-11 10:12

Sungpil's article was close, but didn't quite work. This was the best solution I found for this: https://scriptsandstatistics.wordpress.com/2015/12/18/rmarkdown-how-to-inserts-page-breaks-in-a-ms-word-document/

Even better, the author included the Word template to make this work. The R-blogger's link to his template is broken, and the header is formatted wrong. Some notes I took:

1) You might need to include the whole path to the word template in your Rmd header, like so:

output: 
    word_document:
      reference_docx: C:/workspace/myproject/mystyles.docx

2) The template at the link above changed some of the default style settings so you'll need to change them back

查看更多
We Are One
4楼-- · 2019-01-11 10:13

My solution is not very robust but can work for some of us. Assuming you need a page break before each level 1 title in your word document, I defined this in the format template used in the yaml field reference_docx: . In this document you modify the Heading 1 format (or equivalent) to insert a page break before the Title. Do not forget to start your template with the first docx rendered with knitr (pandoc) in RStudio.

查看更多
登录 后发表回答