adding image in headers and footers in rmarkdown with output as pdf

Viewed 2323

I am trying to create a pdf document with custom headers in RStudio Server but latex is having trouble compiling hence I don't get any output.

I tried following the code provided in Dynamic headers in rmarkdown pdf output in adding images in the headers but this does not seem to be working.

---
    title: ''
    output:
      pdf_document: 
         latex_engine: pdflatex
    classoption: landscape
    geometry: left=0.5in,right=0.5in,top=0.5in,bottom=0.5in
    header-includes: 
      -\usepackage{graphicx}
      -\usepackage{fancyhdr}
      -\pagestyle{fancy}
      -\fancyhead[R]{\includegraphics[width=3cm]{Capture.JPG}}
      -\fancyfoot[R]{\includegraphics[width=3cm]{Capture2.JPG}}
      -\renewcommand{\headrulewidth}{0.4pt}
      -\renewcommand{\footrulewidth}{0.4pt}
---

The error that I'm getting is:

! LaTeX Error: Missing \begin{document}.

Error: Failed to compile Main_pdf.tex. See Main_pdf.log for more info.
In addition: There were 50 or more warnings (use warnings() to see the first 50)
Execution halted

One of the things that I tried to address the concern is by specifying the path to the location of pdf latex but this did not work.

1 Answers

YAML can be rather picky when it comes to formatting. In this case, you need to put a space between - and the following text:

---
    title: ''
    output:
      pdf_document: 
         latex_engine: pdflatex
         keep_tex: yes
    classoption: landscape
    geometry: left=0.5in,right=0.5in,top=0.5in,bottom=0.5in
    header-includes: 
      - \usepackage{graphicx}
      - \usepackage{fancyhdr}
      - \pagestyle{fancy}
      - \fancyhead[R]{\includegraphics[width=3cm]{Capture.JPG}}
      - \fancyfoot[R]{\includegraphics[width=3cm]{Capture2.JPG}}
      - \renewcommand{\headrulewidth}{0.4pt}
      - \renewcommand{\footrulewidth}{0.4pt}
---

BTW, the keep_tex: yes is what I use to debug issues like this. However, in this particular case it was not necessary as the .tex file was still present for inspection, showing the literal -s within the preamble.

Related