Search code examples
rxmldocxofficerxml2

Modify xml_document in officer in R


I have an rdocx and I want to manipulate something in the xml code. That's my document:

library(officer)

doc <- read_docx() %>%
  body_add_par("centered text", style = "centered") %>%
  slip_in_seqfield("STYLEREF 1 \\s") %>% 
  slip_in_text("\u2011") %>% 
  slip_in_seqfield(sprintf("SEQ %s \\* ARABIC \\s 1", "Table")) %>% 
  slip_in_text(str_c(": ", "My Caption")) %>% 
  body_bookmark("my_bookmark")

With doc$doc_obj$get() I can get the xml code with classes xml_document and xml_node. Now I want to replace some code, in detail I want the part with w:bookmarkEnd to appear later so the bookmarked part gets bigger. How can I achieve this? If I could achieve this with str_replace it would be awesome.


Solution

  • You can use run_bookmark() as in the following example (the manual does not state that lists are supported, I'll add that info soon):

    library(officer)
    
    bkm <- run_bookmark(
      bkm = "test",
      list(
        run_word_field(field = "SEQ tab \\* ARABIC \\s"),
        ftext(" Table", prop = fp_text_lite(color = "red"))
      )
    )
    doc <- read_docx()
    
    doc <- body_add_fpar(
      x = doc,
      value = fpar(bkm)
    )
    
    # how to make a reference to the bkm
    doc <- body_add_fpar(
      x = doc,
      value = fpar(run_reference("test"))
    )
    
    print(doc, "zz.docx")
    

    enter image description here