8.3 Style individual elements
Due to the simplicity of Markdown, you can apply some global styles to the Word document (see Section 8.1), but it is not straightforward to style individual elements, such as changing the color of a word, or centering a paragraph.
Continuing his effort to make it easier to work with Office documents in R, David Gohel started to develop the officedown package (Gohel and Ross 2024) in 2018, which aims to bring some officer (Gohel and Moog 2024) features into R Markdown. As of this writing, this package is still experimental, although its initial version has been published on CRAN. You may either install it from CRAN or GitHub:
# install from CRAN
install.packages("officedown")
# or GitHub
::install_github("davidgohel/officedown") remotes
After the package is installed, you need to load it in your R Markdown document, e.g.,
```{r, setup, include=FALSE}
library(officedown)
```
There is an output format rdocx_document
in the officedown package, which is based on rmarkdown::word_document
by default, and has several other features such as styling tables and plots.
The officedown package allows you to style specific Word elements via the officer package. For example, you can create a style via the function officer::fp_text()
, and apply the style to a piece of text via ftext()
an inline R expression:
---
title: Style text with officedown
output:
officedown::rdocx_document: default
---
```{r}
library(officedown)
library(officer)
ft <- fp_text(color = 'red', bold = TRUE)
```
# Test
The **officedown** package is`r ftext('awesome', ft)`!
Besides functions in officer, officedown also allows you to use some special HTML comments to perform officer tasks. For example, the function officer::block_pour_docx()
can be used to import an external Word document into the current document, and alternatively, you can use the HTML comment in R Markdown:
<!---BLOCK_POUR_DOCX{file: 'my-file.docx'}--->
That is equivalent to the inline R expression:
`r block_pour_docx(file = 'my-file.docx')`
Other things you may do with officedown and officer include the following:
Insert page breaks.
Put content in a multi-column layout.
Change paragraph settings.
Insert a table of contents.
Change the orientation of a section (landscape or portrait).
To learn more about officedown, please check out its documentation at https://davidgohel.github.io/officedown/.