11

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]
lowndrul
  • 3,715
  • 7
  • 36
  • 54

1 Answers1

10

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.

eipi10
  • 91,525
  • 24
  • 209
  • 285
  • everything worked for me except for page numbering in the html footer. Is there an easy way to add page-numbering in the html output? – lowndrul Sep 03 '17 at 23:14
  • 2
    The html output is a single html page. How do you want to paginate it? – eipi10 Sep 05 '17 at 03:45
  • I would like to add them to each printed page. But this doesn't seem to be trivial. E.g, [this post](https://stackoverflow.com/questions/1360869/how-to-use-html-to-print-header-and-footer-on-every-printed-page-of-a-document) – lowndrul Sep 05 '17 at 21:36
  • Well, that's above my `html/css` pay grade, but please post your solution if you come up with something that works. – eipi10 Sep 05 '17 at 21:39
  • This is not working when kniting to PDF. Is there something else I must be doing? – Gopala Dec 09 '18 at 04:18