Skip to contents

This function is used to append content to a Word document in a fast way.

It does not use the XML tree of the document neither the cursor that is responsible for increasing the performance of Word document generation when looping over a large number of elements.

This function must be used with the write_elements_to_context() and body_append_stop_context() functions:

  1. body_append_start_context() creates a context and returns a list with the context and the file connection.

  2. write_elements_to_context() writes the elements to the context file connection.

  3. body_append_stop_context() closes the file connection and replaces the XML in the document with the new XML.

Usage

body_append_start_context(x)

write_elements_to_context(context, ...)

body_append_stop_context(context)

Arguments

x

an rdocx object

context

the context object created by body_append_start_context().

...

elements to be written to the context. These can be paragraphs, tables, images, etc. The elements should have an associated to_wml() method that converts them to WML format.

Value

body_append_start_context() returns a list representing the context that contains:

  • doc: the original document object

  • file_con: the file connection to the context

  • file_path: the path to the context file

  • final_str: the final XML string to be appended to the document later when calling body_append_stop_context().

This object should not be modified by the user but instead passed to write_elements_to_context() and body_append_stop_context().

write_elements_to_context() returns the context object.

body_append_stop_context() returns the rdocx object with the cursor position set to the end of the document.

Examples

library(officer)

doc <- read_docx()
doc <- body_add_par(doc, value = "blah blah blah", style = "Normal")

z <- body_append_start_context(doc)

for (i in seq_len(50)) {
  write_elements_to_context(
    context = z,
    fpar(
      "Hello World, ", i,
      fp_p = fp_par(word_style = "heading 1")),
    fpar(run_pagebreak())
  )
}
doc <- body_append_stop_context(z)


print(doc, target = tempfile(fileext = ".docx"))