officer icon indicating copy to clipboard operation
officer copied to clipboard

Replace several bookmarks at once (minor feature request with code suggestion)

Open DanChaltiel opened this issue 4 years ago • 0 comments

Hi David,

I often find myself replacing several bookmarks at once.

Hence, I wrote this little function which has proven pretty handy:

#' @param bkm_list a list where name is the name of the bookmark and value is the replacement text 
body_replace_text_at_bkms = function(x, bkm_list){
  for(i in names(bkm_list)){
    x$doc_obj$cursor_replace_first_text(i, bkm_list[[i]])
  }
  x
}

I'm not sure the for loop is the best design though, as I often read that R for loops are evil, but I couldn't come out with a better idea.

Here is a usage example:

template <- system.file(package = "officer", "doc_examples/example.docx")
img.file <- file.path( R.home("doc"), "html", "logo.jpg" )
bkm_list <- list(bmk_1="I am the Bookmark 1", bmk_2="I am the Bookmark 2")
out=tempfile(fileext = ".docx")
read_docx(path = template) %>% 
  headers_replace_img_at_bkm(bookmark = "bmk_header",
                                  value = external_img(src = img.file, width = .53, height = .7)) %>% 
  # body_replace_text_at_bkm("bmk_1","I am the Bookmark 1") %>% 
  # body_replace_text_at_bkm("bmk_2","I am the Bookmark 2") %>% 
  body_replace_text_at_bkms(bkm_list) %>%
  footers_replace_img_at_bkm(bookmark = "bmk_footer",
                                  value = external_img(src = img.file, width = .53, height = .7)) %>% 
  print(target = out)
shell.exec(out)
#shell.exec(template) for comparison

I did not make a pull request as I'm not sure where you'd want to insert it and how you'd want to merge the documentation. Also, the example in the documentation might be improved by using the pipes and the final exec of my example, if you like the idea.

BTW, docx_bookmarks(read_docx(template)) returns the bookmarks included in the body only, not the ones in the header or the footer. I made sure they were in the template docx in MS Word. This seems like a bug.

Best regards and a happy new year! Dan

DanChaltiel avatar Jan 02 '20 14:01 DanChaltiel