Adrian
Adrian

Reputation: 9793

R: how to change font and alignment of text in knitr word

```{r results = 'asis'}
for(i in 1:10){
  cat(paste("This is iteration number" i))
}
```

After I output the resulting .docx file, the text is left-aligned in size 12 Cambria font by default. How can I change the alignment to center, change the font size, and font type in my .Rmd file?

Upvotes: 4

Views: 8799

Answers (2)

Isaac Zhao
Isaac Zhao

Reputation: 429

The above solution didn't really work for me but I found a tweak to fix.

In Microsoft Word, you want to make sure you modify a section of text in the .docx reference document for each of the styles:

  • First Paragraph
  • Body Text
  • Compact

Changing font size from the home tab won't do anything. You have to right click on the selected style ribbon -> Modify and change the font size in the popup window for that specific style.

Here's a download link that makes the style more similar to SAS outputs when using the cat() function to print text in your .Rmd to word output: https://drive.google.com/file/d/12VZUPXaAGMKPUAJsohZRYQrToFr6awzY/view?usp=sharing

enter image description here

note that I call the file word-style.docx not word-style-02.docx

Upvotes: 1

mysteRious
mysteRious

Reputation: 4294

One way to do this is to use the reference_docx tag in the YAML header like this:

---
title: "Untitled"
author: "Me X. Person"
date: "April 3, 2018"
output:
  word_document:
    reference_docx: word-style-02.docx
fontsize: 10pt
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

```{r results = 'asis'}
for(i in 1:10){
  cat(paste("This is iteration number", i, "<P><br>"))
}
```

Next, prepare a file in Word where all you do is control the styles -- I knit to Word and found out that in this example, the code is controlled by the style titled Compact. So I clicked on that square in the ribbon in the MS Word header, and set it to 16 point Courier New (centered). The Word file that I used is here so you can download and open/try it: Drive link

The output it generates looks like this in Word:

enter image description here

If this is way off of what you were looking for, just let me know and I will delete it. Hopefully it is at least little bit useful.

Upvotes: 7

Related Questions