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.
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) ```
Building upon previous solutions, the following solution does not require an auxiliary header.tex
file. All contents are contained in the .Rmd
file. The LaTeX commands are instead defined in a header-includes
block in the YAML header. More info can be found here.
Also, I noticed that using the lscape
LaTeX package rotates the contents of a page, but not the PDF page itself. This is resolved using the pdflscape
package.
--- title: "Mixing portrait and landscape WITHOUT a header.tex file" header-includes: - \usepackage{pdflscape} - \newcommand{\blandscape}{\begin{landscape}} - \newcommand{\elandscape}{\end{landscape}} output: pdf_document --- Portrait ```{r} summary(cars) ``` \newpage \blandscape Landscape ```{r} summary(cars) ``` \elandscape \newpage More portrait ```{r} summary(cars) ```
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With