| as_word_field | R Documentation |
as_word_field() inserts a Word field code (e.g. page
numbers, dates, cross-references) as a chunk inside a
flextable cell. Field codes are Word's mechanism for
auto-computed values; see
Microsoft's field-code reference
for the available codes.
The chunk is used with compose(), append_chunks()
or prepend_chunks(). It only has an effect in Word
(docx) output; other formats ignore it. To apply it
conditionally, use the post-processing step (see
set_flextable_defaults(post_process_docx = ...)).
Important: fields are inserted but not computed.
After opening the document in Word, select all text
and press F9 (on macOS: Fn + F9) to refresh the
field values.
as_word_field(x, props = NULL, width = 0.1, height = 0.15, unit = "in")
x |
computed field strings |
props |
text properties (see |
width, height |
size computed field |
unit |
unit for width and height, one of "in", "cm", "mm". |
Other chunk elements for paragraph:
as_b(),
as_bracket(),
as_chunk(),
as_equation(),
as_highlight(),
as_i(),
as_image(),
as_qmd(),
as_strike(),
as_sub(),
as_sup(),
colorize(),
gg_chunk(),
grid_chunk(),
hyperlink_text(),
linerange(),
minibar(),
plot_chunk()
library(flextable)
# define some default values ----
set_flextable_defaults(font.size = 22, border.color = "gray")
# an example with append_chunks ----
pp_docx <- function(x) {
x <- add_header_lines(x, "Page ")
x <- append_chunks(
x = x, i = 1, part = "header", j = 1,
as_word_field(x = "Page")
)
align(x, part = "header", align = "left")
}
ft_1 <- flextable(cars)
ft_1 <- autofit(ft_1)
ft_1 <- pp_docx(ft_1)
## or:
# set_flextable_defaults(post_process_docx = pp_docx)
## to prevent this line addition when output is not docx
# print(ft_1, preview = "docx")
# an example with compose ----
library(officer)
ft_2 <- flextable(head(cars))
ft_2 <- add_footer_lines(ft_2, "temp text")
ft_2 <- compose(
x = ft_2, part = "footer", i = 1, j = 1,
as_paragraph(
"p. ",
as_word_field(x = "Page", width = .05),
" on ", as_word_field(x = "NumPages", width = .05)
)
)
ft_2 <- autofit(ft_2, part = c("header", "body"))
doc <- read_docx()
doc <- body_add_flextable(doc, ft_2)
doc <- body_add_break(doc)
doc <- body_add_flextable(doc, ft_2)
outfile <- print(doc, target = tempfile(fileext = ".docx"))
# reset default values ----
init_flextable_defaults()
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.