
Last chance! 50% off unlimited learning
Sale ends in
a set of functions is available to manipulate the position of a virtual cursor. This cursor will be used when inserting, deleting or updating elements in the document.
cursor_begin(x)cursor_bookmark(x, id)
cursor_end(x)
cursor_reach(x, keyword)
cursor_forward(x)
cursor_backward(x)
a docx device
bookmark id
keyword to look for
Set the cursor at the beginning of the document, on the first element of the document (usually a paragraph or a table).
Set the cursor at the end of the document, on the last element of the document.
Set the cursor on the first element of the document
that contains text specified in argument keyword
.
Move the cursor forward, it increments the cursor in the document.
Move the cursor backward, it decrements the cursor in the document.
library(officer)
library(magrittr)
doc <- read_docx() %>%
body_add_par("paragraph 1", style = "Normal") %>%
body_add_par("paragraph 2", style = "Normal") %>%
body_add_par("paragraph 3", style = "Normal") %>%
body_add_par("paragraph 4", style = "Normal") %>%
body_add_par("paragraph 5", style = "Normal") %>%
body_add_par("paragraph 6", style = "Normal") %>%
body_add_par("paragraph 7", style = "Normal") %>%
# default template contains only an empty paragraph
# Using cursor_begin and body_remove, we can delete it
cursor_begin() %>% body_remove() %>%
# Let add text at the beginning of the
# paragraph containing text "paragraph 4"
cursor_reach(keyword = "paragraph 4") %>%
slip_in_text("This is ", pos = "before", style = "Default Paragraph Font") %>%
# move the cursor forward and end a section
cursor_forward() %>%
body_add_par("The section stop here", style = "Normal") %>%
body_end_section(landscape = TRUE) %>%
# move the cursor at the end of the document
cursor_end() %>%
body_add_par("The document ends now", style = "Normal")
print(doc, target = "cursor.docx")
# cursor_bookmark ----
library(magrittr)
doc <- read_docx() %>%
body_add_par("centered text", style = "centered") %>%
body_bookmark("text_to_replace") %>%
body_add_par("A title", style = "heading 1") %>%
body_add_par("Hello world!", style = "Normal") %>%
cursor_bookmark("text_to_replace") %>%
body_add_table(value = iris, style = "table_template")
print(doc, target = "bookmark.docx")
Run the code above in your browser using DataLab