Rstudio rmarkdown: both portrait and landscape layout in a single PDF

user3712688 picture user3712688 · Sep 15, 2014 · Viewed 45.6k times · Source

I wonder how to use rmarkdown to generate a pdf which has both portrait and landscape layout in the same document. If there is a pure rmarkdown option that would be even better than using latex.

Here's a small, reproducible example. First, rendering this .Rmd in RStudio (press Knit PDF button) results in a pdf with all pages in landscape layout:

---
title: "All pages landscape"
output: pdf_document
classoption: landscape
---

```{r}
summary(cars)
```

\newpage
```{r}
summary(cars)
```

Then an attempt to create a document which mixes portrait and landscape layout. The basic setup in the YAML is done according to the 'Includes' section here. The in_header file 'header.tex' only contains \usepackage{lscape}, a package suggested for knitr landscape layout here. The .tex file is in the same directory as the .Rmd file.

---
title: "Mixing portrait and landscape"
output:
    pdf_document:
        includes:
            in_header: header.tex
---

Portrait:
```{r}
summary(cars)
```

\newpage
\begin{landscape}
Landscape:
```{r}
summary(cars)
```
\end{landscape}

\newpage
More portrait:
```{r}
summary(cars)
```

However, this code results in an error:

# ! You can't use `macro parameter character #' in horizontal mode.
# l.116 #

# pandoc.exe: Error producing PDF from TeX source
# Error: pandoc document conversion failed with error 43

Any help is much appreciated.

Answer

baptiste picture baptiste · Dec 6, 2014

So, pandoc does not parse the content of latex environments, but you can fool it by redefining the commands in your header.tex file:

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

Thus, here \begin{landscape} is redefined to \blandscape, and \end{landscape} to \elandscape. Using those newly defined command in the .Rmd file seems to work:

---
title: "Mixing portrait and landscape"
output:
    pdf_document:
        includes:
            in_header: header.tex 
---

Portrait
```{r}
summary(cars)
```

\newpage
\blandscape
Landscape
```{r}
summary(cars)
```
\elandscape

\newpage
More portrait
```{r}
summary(cars)
```