0

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.

TobiSonne
  • 1,044
  • 7
  • 22
  • Please don't use internals, use `officer::docx_body_xml()` instead of `doc$doc_obj$get()`, unless you want to risk an unwanted breaking change :). Also, you are using `slip_in_*` that all are deprecated or defunct and should be replaced by calls to `fpar(run_...)`. About your question, I don't think you can with str_replace, but it should be ok using the documented function `officer::run_bookmark()` – David Gohel May 30 '22 at 14:02
  • Thank you for quick answer, I've hoped that you would reply to me question and I would prefer a way with `run_bookmark, too`. Do you have an idea how I can get a bookmark from the beginning until `"SEQ %s \\* ARABIC \\s 1 Table"`? I've already tried it but without any success :( – TobiSonne May 30 '22 at 14:08

1 Answers1

1

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

David Gohel
  • 9,180
  • 2
  • 16
  • 34