Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mixed Landscape + Portrait pages when generating word document from RMarkdown

I'm trying to create a word document from RMarkdown-so far everything has been great except that I have to output a 4 page report, the first page being a portrait, the following 2 pages with ggplots being landscape and the last page with a ggplot in portrait.

I've tried every solution I can think of. I've made 4 pages in a reference docx that have the orientations I need, but that didn't work. I also tried this solution using a header.tex file that would contain this:

\usepackage{lscape}
\newcommand{\blandscape}{\begin{landscape}}
\newcommand{\elandscape}{\end{landscape}}

and this solution I saw on StackOverflow using a lua filter in pandoc_args.

---
title: "Example"
output: 
  word_document:
    pandoc_args:
     '--lua-filter=page-break.lua'
---

The solution that would solve my problem would be this argument from the officedown package: https://github.com/davidgohel/officedown

<!---BLOCK_LANDSCAPE_START--->

Blah blah blah.

<!---BLOCK_LANDSCAPE_STOP--->

but unfortunately I cannot download it using devtools() off my work RServer where I need it. Is there any way I can use and manipulate some functions in officer (the non-markdown version of officedown) to get a mix of portrait and landscape orientations in my document? For example, the officer package has this function: https://github.com/davidgohel/officer/blob/master/R/docx_section.R

body_end_section_landscape <- function( x, w = 21 / 2.54, h = 29.7 / 2.54 ){
  w = w * 20 * 72
  h = h * 20 * 72
  pgsz_str <- "<w:pgSz w:orient=\"landscape\" w:w=\"%.0f\" w:h=\"%.0f\"/>"
  pgsz_str <- sprintf(pgsz_str, h, w )
  str <- sprintf( "<w:pPr><w:sectPr><w:officersection/>%s</w:sectPr></w:pPr>", pgsz_str)
  str <- paste0( wp_ns_yes, str, "</w:p>")
  as_xml_document(str)
  body_add_xml(x, str = str, pos = "after")
}

#' @export
#' @rdname sections
body_end_section_portrait <- function( x, w = 21 / 2.54, h = 29.7 / 2.54 ){
  w = w * 20 * 72
  h = h * 20 * 72
  pgsz_str <- "<w:pgSz w:orient=\"portrait\" w:w=\"%.0f\" w:h=\"%.0f\"/>"
  pgsz_str <- sprintf(pgsz_str, w, h )
  str <- sprintf( "<w:pPr><w:sectPr><w:officersection/>%s</w:sectPr></w:pPr>", pgsz_str)
  str <- paste0( wp_ns_yes, str, "</w:p>")
  body_add_xml(x, str = str, pos = "after")
}

Thanks!

like image 430
figuringitout101 Avatar asked Oct 23 '25 15:10

figuringitout101


1 Answers

Hi there I was able to do this yesterday using the officedown package. Once you install it you can go File >New File > RMarkdown and pick From Template where you can select Advanced Word document. The example they give you in the template shows both portrait and landscape.

like image 152
Patrick Avatar answered Oct 25 '25 06:10

Patrick