You can apply the styles defined in a Word template document to new Word documents generated from R Markdown. Such a template document is also called a “style reference document.” The key is that you have to create this template document from Pandoc first, and change the style definitions in it later. Then pass the path of this template to the reference_docx option of word_document, e.g.,

    1. ---
    2. output:
    3. word_document:
    4. reference_docx: "template.docx"
    5. ---

    As we just mentioned, the document template.docx has to be generated from Pandoc. You can create this template from an arbitrary R Markdown document with the word_document output format (the actual content of this document does not matter, but it should contain the type of elements of which you want to style). Then open the .docx file, and edit the styles.

    Image 1: Find the styles of a specific document element.

    FIGURE 8.1: Find the styles of a specific document element.

    Figure 8.1 shows that you can open the “Styles” window from the “HOME” tab in Word. When you move the cursor to a specific element in the document, an item in the styles list will be highlighted. If you want to modify the style of any type of element, you can click the drop-down menu on the highlighted item, and you will see a dialog box like Figure 8.2.

    Image 2: Modify the styles of an element in a Word document.

    FIGURE 8.2: Modify the styles of an element in a Word document.

    After you finish modifying the styles, you can save the document (with a filename that will not be accidentally overwritten), and use it as the template for future Word documents. When Pandoc renders a new Word document with a reference document (template), it will read the styles in the template and apply them to the new document.

    You may watch a short video at https://vimeo.com/110804387, or read the article at https://rmarkdown.rstudio.com/articles_docx.html for more detailed instructions on how to create a Word template with custom styles.

    Sometimes it may not be straightforward to find the style name for an element. There may be multiple styles applied to the same element, and you will only see one of them highlighted in the list of styles. It may require some guesswork and online searching to figure out the actual style that you want to modify. For example, you have to click the “Manage Styles” button (the third button from left to right at the bottom of the style list in Figure 8.1), and scroll through a large number of style names before you find the “Table” style (see Figure 8.3). Then you can modify this style for your tables (e.g., add borders).

    Image 3: Modify the styles of tables in a Word document.

    FIGURE 8.3: Modify the styles of tables in a Word document.