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:
body_append_start_context()
creates a context and returns a list with the context and the file connection.write_elements_to_context()
writes the elements to the context file connection.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, additional_ns = character())
write_elements_to_context(context, ...)
body_append_stop_context(context)
Arguments
- x
an rdocx object
- additional_ns
a named character vector of additional XML namespaces to be added to the root node of the document. The names of the vector are the namespace prefixes and the values are the namespace URIs.
This argument is useful when the elements to be added to the document require additional namespaces that are not already present in the document and not part of the xml generated by
to_wml()
. Simple users are not expected to use this argument. It is mainly intended for developers of officer extensions.- 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 objectfile_con
: the file connection to the contextfile_path
: the path to the context filefinal_str
: the final XML string to be appended to the document later when callingbody_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.
See also
Other functions for adding content:
body_add_blocks()
,
body_add_break()
,
body_add_caption()
,
body_add_docx()
,
body_add_fpar()
,
body_add_gg()
,
body_add_img()
,
body_add_par()
,
body_add_plot()
,
body_add_table()
,
body_add_toc()
,
body_import_docx()
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"))