Inserting a page break within a code chunk in rmarkdown (converting to pdf)

How to insert a page break within an Rstudio .Rmd code chunk that survives conversion to PDF:

If the \newpage and \pagebreak latex macros aren't working for you, here's a workaround using HTML.

For example:

---
title: "The Rent"
output:
  pdf_document: default
  html_document: default
---

# This is pre-chunk text.

```{r, echo=FALSE, results='asis'}
print("Now we're <b>inside the chunk</b>, using the power of HTML.<br><br><br>!")

print("As you can see from the following diagram")
cat("\n")
print("The rent...<br>")
print(plot(1:10))

print("<P style='page-break-before: always'>")    #forced new-page happens here.

print("<h1>Is too damned high!!</h1>")
writeLines("\n")
print("Finished")
cat("\n\n")
```
This is post chunk text.

Produces this for me:

enter image description here

The key ingredients is the print("<P style='page-break-before: always'>") and the {r, echo=FALSE, results='asis'} in the chunk header.


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 an Undefined 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")
    }
    ```