0

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)
    }
  }
}
kenlukas
  • 3,616
  • 9
  • 25
  • 36
morgan121
  • 2,213
  • 1
  • 15
  • 33

2 Answers2

2

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 }

David Gohel
  • 9,180
  • 2
  • 16
  • 34
  • On another note, is there way to automatically calculate and add column sums into the footer of a table? – morgan121 Oct 03 '18 at 04:02
0

After a bit more digging there is a workaround where you add set_curser(x, bookmarkID) before the body_add_flextable(x, flextable) command.

For consistaency it would still be nice to have the body_flextable_at_bkm as part of the flextable package so it can be used like headers_flextable_at_bkm and footers_flextable_at_bkm commands.

Edit: the body_flextable_at_bkm command should now work with the latest version of the package.

morgan121
  • 2,213
  • 1
  • 15
  • 33