Search code examples
rflextableofficer

Add a flextable at a bookmark in the body of a word document from R


I'm trying to add a flextable at a specific bookmark within the body of a Word document. So far I have found the following options:

  • footers_flextable_at_bkm {flextable}
  • headers_flextable_at_bkm {flextable}
  • body_add_flextable {flextable}

But none of them do exactly what I need.

I tried to write my own code to do it (see below), but it says that the docx_str function is not found. (I coped/modified this code from the headers_flextable_at_bkm function). Does anyone have a way to do this? Or is it a fuction that could be added to the flextable package?

body_flextable_at_bkm <- function(x, bookmark, value){

  stopifnot(inherits(x, "rdocx"), inherits(value, "flextable"))

  str <- docx_str(value, doc = x, align = "center")

  xml_elt <- as_xml_document(x)

  for(doc_obj in x$body){
    if( doc_obj$has_bookmark(bookmark) ){
       doc_obj$cursor_bookmark(bookmark)
       cursor_elt <- doc_obj$get_at_cursor()
       xml_replace(cursor_elt, xml_elt)
    }
  }
}

Solution

  • This function should do what you need:

    body_flextable_at_bkm <- function(x, bookmark, value){ x <- cursor_bookmark(x, bookmark) x <- body_add_flextable(x = x, value = value, pos = "on") x }