Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic header/footer in R-Markdown knit to word?

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
---
like image 963
LTravis Avatar asked Oct 29 '25 05:10

LTravis


1 Answers

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")
like image 122
JuergenL Avatar answered Oct 31 '25 21:10

JuergenL



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!