lowndrul
lowndrul

Reputation: 3815

In R Markdown, create header/footer on every page regardless of output type (pdf, html, docx)

I'd like to add to the question Creating a footer for every page (including first!) using R markdown. The code there (also, below) works perfectly fine for me when knitting to pdf. But I won't get header/footers for html or docx output.

In R Markdown, what can I do to generate header/footers for every page of an output doc regardless of the type of output doc?

---
title: "Test"
author: "Author Name"
header-includes:
- \usepackage{fancyhdr}
- \usepackage{lipsum}
- \pagestyle{fancy}
- \fancyhead[CO,CE]{This is fancy header}
- \fancyfoot[CO,CE]{And this is a fancy footer}
- \fancyfoot[LE,RO]{\thepage}
output: pdf_document
---
\lipsum[1-30]

Upvotes: 11

Views: 17253

Answers (1)

eipi10
eipi10

Reputation: 93761

You can add YAML instructions for headers and footers in html and Word versions of the document. Below is what the YAML looks like. Explanations follow.

---
title: "Test"
author: "Author Name"
output:
  html_document:
    include:
      before_body: header.html
      after_body: footer.html
  pdf_document: 
  word_document: 
   reference_docx: template.docx
header-includes:
  - \usepackage{fancyhdr}
  - \usepackage{lipsum}
  - \pagestyle{fancy}
  - \fancyhead[CO,CE]{This is fancy header}
  - \fancyfoot[CO,CE]{And this is a fancy footer}
  - \fancyfoot[LE,RO]{\thepage}
---

html header and footer

As shown in the YAML above, for html output you can specify the header and footer in separate html files using the before_body: and after_body: tags. For example, to get a header followed by a rule line, the header.html file could look like this:

This is a header
<hr>

Word header and footer

Yihui Xie, author of knitr, explains how to do this here (also see this SO answer). You create a Word file with the styles you want and then save that file in the local directory (or you can provide a path to the file if it's in another directory). Then you use the reference_docx: YAML tag to point knitr to that document. I just opened a new Word file and added a header and footer and then saved the file as template.docx in the local directory.

Upvotes: 12

Related Questions