1

I am generating a number of reports using an RMarkdown script. I would like to add a custom header/footer to the word-document output using a parameter, e.g. client_name. When I render the RMarkdown from a separate script, it loops through the list of clients and changes the data. I would like the header to update as well.

I have tried the answers from this question with no luck, as well as used a word reference document to set the header. However with the reference document, I can only set a static header that is not updated when the parameter changes.

Header should show:

Steve
August 06, 2021
Page X of 3

With "Steve" updated to a different name upon looping.
Here's what I have in my YAML:

---
title: "test doc"
author: 
- Author 1
- Author 2
date: "`r format(Sys.time(), '%B %d, %Y')`"
output: 
  word_document:
    reference_docx: test1.docx
params: 
  client: "Steve"
header-includes:
   - \usepackage{fancyhdr}
   - \usepackage{lipsum}
   - \pagestyle{fancy}
   - \fancyhead[LE,L0]{"params$client <br> `r format(Sys.time(), '%B %d, %Y')` <br> Page \thepage of 3"}
  
always_allow_html: true
---
LTravis
  • 11
  • 2

2 Answers2

1

I have implemented that in two steps:

  1. Use a Word template (as reference_docx) that contains a dummy header (e.g., "mydummyheader").
  2. To render the .rmd file, you use an R program (not interactively in R Studio).
  3. In the same R program, after having created the Word document with your contents, you use the {officer} library to replace your dummy header with the one that you want. Example code (also replacing a dummy footer):
    library(magrittr)
    library(officer)
    rmarkdown::render("mytest.Rmd", output_format = "word_document",
                       output_file = "mytest.docx")
    read_docx("mytest.docx") %>%              
    headers_replace_all_text("mydummyheader", "myrealheader") %>%               
    footers_replace_all_text("mydummyfooter", "myrealfooter") %>%
    print(target = "mytest_updated.docx")
JuergenL
  • 131
  • 1
  • 6
-2

Use a custom document property with the name ClientName. In the Header of the document, have a field { DocProperty ClientName}.

Change the document property with your code.

See How to use a single VBA procedure to read or write both custom and built-in Document Properties by Word MVP Astrid Zeeland. This gives the vba for dealing with this.

Sorry, I know nothing about R-Markdown but expect that you will need the vba to change the Word document.

Charles Kenyon
  • 869
  • 1
  • 8
  • 19