MS Word number of pages in a flextable table using Rmarkdown

243 Views Asked by At

Is there a way to insert MS Word computed field - total number of pages in the document - into a flextable table?

In the officer package there's a function run_word_field. I tried to use it the following way:

flextable(df) %>%
  compose(value = as_paragraph(
    as_chunk(run_word_field(field = "NumPages  \\* MERGEFORMAT"))
  ))

but it throws an error.

Is there a workaround?

1

There are 1 best solutions below

0
On BEST ANSWER

You can now use function as_word_field:

library(flextable)
library(officer)

# define some default values ----
set_flextable_defaults(font.size = 22, border.color = "gray")

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"),
               " on ", as_word_field(x = "NumPages"))
)
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")) 

enter image description here