How to add a page break in word document generated by RStudio & markdown
Added: To insert a page break, please use \newpage
for formats including LaTeX, HTML, Word, and ODT.
https://bookdown.org/yihui/rmarkdown-cookbook/pagebreaks.html
Paragraph before page break.
\newpage
First paragraph on a new page.
Previously: There is a way by using a fifth-level header block (#####
) and a docx template defined in YAML.
After creating headingfive.docx
in Microsoft Word, you select Modify Style
of the Heading 5
, and then select Page break before
in the Line and Page Breaks
tab and save the headingfive.docx
file.
---
title: 'Making page break using fifth-level header block'
output:
word_document:
reference_docx: headingfive.docx
---
In your Rmd
document, you define reference_docx
in the YAML header, and now you can use the page-breaking #####
.
Please see below.
https://www.r-bloggers.com/r-markdown-how-to-insert-page-breaks-in-a-ms-word-document/
page break for pdf and word in rmarkdown
Many thanks to tarleb for the answer. As suggested I used your answer to this post: https://stackoverflow.com/a/52131435/2425163.
step 1: create a txt file with the following code:
--- 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
step 2: save the file as page-break.lua in the same directory with my R Markdown file.
step 3: add the link as pandoc argument.
This the reproducible example (R Markdown file) corrected:
---
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.
Please note that this may not work for the toc, but i don't use the lua filter with pdf and with word _document it's very easy to add the table of content afterwards directly in Word. Plus there is a link to a solution for that problem in the above link.
How to add \newpage in Rmarkdown in a smart way?
Simply \newpage
or \pagebreak
will work, e.g.
hello world
\newpage
```{r, echo=FALSE}
1+1
```
\pagebreak
```{r, echo=FALSE}
plot(1:10)
```
This solution assumes you are knitting PDF. For HTML, you can achieve a similar effect by adding a tag <P style="page-break-before: always">
. Note that you likely won't see a page break in your browser (HTMLs don't have pages per se), but the printing layout will have it.
Inserting a page break within a code chunk in rmarkdown (converting to pdf)
See below a reduced and reproducible example. The answer and some general remarks:
- To dynamically create new pages or sections in a markdown document use
results='asis'
in the chunk options. - You have to add a linebreak (
\n
) after\\pagebreak
or else"ValueForV"
will be pasted directly after"\linebreak"
, which results in anUndefined control sequence
error. - Make sure that
\newpage
and\pagebreak
are in a separate line by using linebreaks\n
before. Escape
\newpage
and\pagebreak
(i.e.,\\newpage
,\\pagebreak
).---
title: "test"
output: pdf_document
---
```{r, echo=FALSE, results='asis'}
for (i in 1:3) {
print(ggplot2::qplot(i, i+1))
cat("\n\n\\pagebreak\n")
writeLines("ValueForV")
}
```
knitr/Rmd: Adding title page and text when converting to MS Word
I have found that it's possible to customize the content of the Markdown file (e.g. to add and modify a title page) generated by rmarkdown
before submitting it to pandoc
for the conversion to DOCX
by using a preprocessor. Let's assume we are trying to add some information specified in a YAML parameter note
just before the abstract (support for abstracts has in the meantime been added to pandoc
).
To do so, we first need a preprocessor function that reads the input file and parses the YAML front matter, and customizes the input file:
my_pre_processor <- function(metadata, input_file, runtime, knit_meta, files_dir, output_dir, from) {
# Identify YAML front matter delimiters
input_text <- readLines(input_file, encoding = "UTF-8")
yaml_delimiters <- grep("^(---|\\.\\.\\.)\\s*$", input_text)
if(length(yaml_delimiters) >= 2 &&
(yaml_delimiters[2] - yaml_delimiters[1] > 1) &&
grepl("^---\\s*$", input_text[yaml_delimiters[1]])) {
yaml_params <- yaml::yaml.load(paste(input_text[(yaml_delimiters[1] + 1):(yaml_delimiters[2] - 1)], collapse = "\n"))
} else yaml_params <- NULL
# Modify title page
custom_lines <- c(
"NOTE:"
, metadata$note
, "\n\n"
, "# Abstract"
, "\n"
, metadata$abstract
, "\n"
)
## Add modified title page components after YAML front matter
augmented_input_text <- c(custom_lines, input_text[(yaml_delimiters[2] + 1):length(input_text)])
# Remove redundant default abstract
yaml_params$abstract <- NULL
# Add modifications to input file
augmented_input_text <- c("---", yaml::as.yaml(yaml_params), "---", augmented_input_text)
input_file_connection <- file(input_file, encoding = "UTF-8")
writeLines(augmented_input_text, input_file_connection)
close(input_file_connection)
NULL
}
Now we need to define a custom format that utilizes our preprocessor:
my_word_document <- function(...) {
config <- rmarkdown::word_document(...)
# Preprocessor functions are adaptations from the RMarkdown package
# (https://github.com/rstudio/rmarkdown/blob/master/R/pdf_document.R)
pre_processor <- function(metadata, input_file, runtime, knit_meta, files_dir, output_dir, from = .from) {
# save files dir (for generating intermediates)
saved_files_dir <<- files_dir
args <- my_pre_processor(metadata, input_file, runtime, knit_meta, files_dir, output_dir, from)
args
}
config$pre_processor <- pre_processor
config
}
Now, you can use the custom format when rendering R Markdown documents as follows:
rmarkdown::render("./foo/bar.Rmd", output_format = my_word_document())
In Markdown PDF, how to add page break after each iteration of for loop?
You can put \\newpage
inside the cat
function to add a page break after each iteration of the loop. The chunk also needs to have the parameter results="asis"
. For example, does something like this work for you:
```{r echo=FALSE, results="asis", warning=FALSE}
library(xtable)
exampledf <- data.frame(column = c("exampletext1", "exampletext2", "exmapletext3"))
for (i in 1:nrow(exampledf)) {
# Just added this as another way of displaying a row of data
print(xtable(exampledf[i, , drop=FALSE]), comment=FALSE)
print(strwrap(exampledf[i,], 70))
cat("\n\\newpage\n")
}
```
Related Topics
Looping Through List of Data Frames in R
Filter a Vector of Strings Based on String Matching
Remove Part of a String in Dataframe Column (R)
Passing Along Ellipsis Arguments to Two Different Functions
Explicitly Set Panel Size (Not Just Plot Size) in Ggplot2
Repeating Rows of Data.Frame in Dplyr
R: Updating a Data Frame with Another Data Frame
Continuous Colour of Geom_Line According to Y Value
Convert a Dataframe to an Object of Class "Dist" Without Actually Calculating Distances in R
Output a Good-Looking Matrix Using Rendertable()
Set Number of Columns (Or Rows) in a Facetted Plot
Time Series Plot with X Axis in "Year"-"Month" in R
How to Filter Data Frame with Conditions of Two Columns
Dealing with Spaces and "Weird" Characters in Column Names with Dplyr::Rename()
Reduce File Size of R Markdown HTML Output