I am stacking two docx, both of which have distinct dates in the title property, linked to a field in the respective document. I would like the date in docx1 to remain unchanged in the new combined docx ("current.docx") as it is when printed in "docx1.docx", but the natural behavior is for docx2 to also update the field in docx1 to its title property once it has been added with body_add_docx()
and printed.
library(officer)
# Set dates for docx1 and docx2
date1 <- format(Sys.Date(), "%A, %B %d, %Y")
date2 <- format(Sys.Date() +1, "%A, %B %d, %Y")
# Create docx1 with date1
docx1 <- read_docx()
docx1 <- set_doc_properties(docx1, title = date1)
fp <- fpar(
ftext("Hello"),
run_linebreak(),
run_word_field(field = "DOCPROPERTY \"title\""),
run_pagebreak()
)
docx1 <- body_add_fpar(docx1, value = fp)
print(docx1, "doc1.docx")
# Create docx2 with date2, and add docx1 as "current.docx" to show how date1 updates to date2
docx2 <- read_docx()
docx2 <- set_doc_properties(docx2, title = date1)
fp <- fpar(
ftext("World"),
run_linebreak(),
run_word_field(field = "DOCPROPERTY \"title\"")
)
docx2 <- body_add_fpar(docx2, value = fp)
docx2 <- body_add_docx(docx2, "doc1.docx")
print(docx2, "current.docx")
# Create example "desired.docx" retaining date1 and date2 after stacking
docx3 <- read_docx()
fp <- fpar(
ftext("Hello"),
run_linebreak(),
ftext(date1),
run_pagebreak(),
ftext("World"),
run_linebreak(),
ftext(date2)
)
docx3 <- body_add_fpar(docx3, value=fp) |>
print("desired.docx")
Created on 2023-07-21 with reprex v2.0.2
Once I have printed docx1, I no longer need the title field, so it seems like converting that field specifically (or even all docx1 fields) to text before printing would make sense as a way of preventing the update. I have tried body_replace_all_text()
, but that doesn't work because there is no text actual text to find in the field. I have also considered that fields can be converted to text in a word document using Ctrl+Shift+F9 to run the "Selection.Range.Field.Unlink" macro, but am not sure how to do this programatically on many documents using R.
Thank you so much for the package and any guidance you can give.