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 2020) in 2018, which aims to bring some officer (Gohel 2020b) 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:

  1. # install from CRAN
  2. install.packages("officedown")
  3. # or GitHub
  4. remotes::install_github("davidgohel/officedown")

After the package is installed, you need to load it in your R Markdown document, e.g.,

  1. ```{r, setup, include=FALSE}
  2. library(officedown)
  3. ```

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:

  1. ---
  2. title: Style text with officedown
  3. output:
  4. officedown::rdocx_document: default
  5. ---
  6. ```{r}
  7. library(officedown)
  8. library(officer)
  9. ft <- fp_text(color = 'red', bold = TRUE)
  10. ```
  11. # Test
  12. The **officedown** package is
  13. `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:

  1. <!---BLOCK_POUR_DOCX{file: 'my-file.docx'}--->

That is equivalent to the inline R expression:

  1. `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/.

References

———. 2020b. Officer: Manipulation of Microsoft Word and PowerPoint Documents. https://CRAN.R-project.org/package=officer.

Gohel, David, and Noam Ross. 2020. Officedown: Enhanced r Markdown Format for Word and PowerPoint. https://davidgohel.github.io/officedown.