2

I'm trying to switch from ReporteRs to officer. When using ReporteRs, I was able to add a FlexTable to the header by using a bookmark that I set up in a Word document template (I placed a bookmark in the header of the template called "HEAD"):

library(ReporteRs)
library(dplyr)
doc <- docx(template = "Template.docx")
ft1 <- FlexTable(mtcars)
addFlexTable(doc,
             ft1,
             bookmark = "HEAD")
writeDoc(doc, file = "test.docx")

Presumably, it might be possible do the same thing using officer with the flextable package, and it might look something like this:

library(officer)
library(flextable)
library(dplyr)
doc <- docx(template = "Template.docx")
ft1 <- flextable(mtcars)
doc <- cursor_bookmark(doc,"HEAD") %>% body_add_flextable(ft)
print(doc,target="test.docx")

If I have a bookmark named "HEAD" in the body of the document, this works, but if I have a bookmark named "HEAD" in the header of the Word document, it says Error: cannot find bookmark "HEAD".

I know there are specific functions to add text to the header, but these don't have the ability to add tables. The closest I can find is:

doc <- docx(template = "Template.docx")
ft1 <- flextable(mtcars)
doc <- headers_replace_text_at_bkm(doc,"HEAD",ft)
print(doc,target="test.docx")

But this returns the error Error in headers_replace_text_at_bkm(doc, "HEAD", ft) : is_scalar_character(value) is not TRUE.

Is there any way to add a table to the header using officer and flextable?

Sam Dickson
  • 5,082
  • 1
  • 27
  • 45
  • 1
    No it does not exist but I can add a function for that in `flextable` (I am the author). I will let you know when it will be ready. – David Gohel Jul 09 '18 at 07:46
  • Thank you, @DavidGohel! I did find a way to do what I wanted. The table I want inserted is fairly standard from document to document, so my template has the table in it and I just replace text in each cell using `headers_replace_text_at_bkm()`. This won't work as well for the footer, since I need the number of rows in the table to vary, but maybe this means that I just need to have multiple templates depending on how many rows I want in the table. A function to insert tables into the header or footer would be awesome, though. – Sam Dickson Jul 10 '18 at 15:12
  • 1
    no problem, I did not think about this use case and it makes sense. You can have a look on github, the new version is providing `headers_flextable_at_bkm` and `footers_flextable_at_bkm`. feedback is welcome! – David Gohel Jul 10 '18 at 17:20

0 Answers0