Search code examples
rr-markdownshowtext

Using Google Fonts in RMarkdown main body without admin privileges


I want to define the fonts to use in my RMarkdown PDF document. I’d like to use a Google Font, say, Roboto, but I do not have admin privileges to install it directly. Nevertheless, I think that I can work around these privileges, as I’ve installed many R packages that come parcelled with their own fonts (e.g., tint).

Normally, to set a custom font for the markdown document I’d do something like this in my YAML:

---
title: "Title"
output:
  pdf_document:
    latex_engine: xelatex
mainfont: Calibri
---

This works if the font is installed, but, as I say, I cannot install fonts. I can use Google Fonts through the showtext package, like in my example below, but this is only for figures:

---
title: "Title"
output:
  pdf_document
---

# Header One  

## Header Two
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

```{r fonts, message=FALSE}
library(showtext)
font_add_google("Lobster", "lobster")
```

```{r fig.showtext=TRUE, fig.align='center'}
plot(1, pch = 16, cex = 3)
text(1, 1.1, "A fancy dot", family = "lobster", col = "steelblue", cex = 3)
```

enter image description here

As you can see, I use the Lobster font in my figure, which is great. I’d like to extend this example so that the Lobster font is used to the main body of the document, but doesn’t need to be installed directly. Is this possible?


Solution

  • As @camille mentioned above, tint installs TeX packages to use fonts. (There's a pretty extensive list of font packages here, including Google Fonts like Roboto.) If I wanted to use Lobster for the main body, I could include the appropriate TeX file in the header like this and it's downloaded and installed automatically upon knitting:

    ---
    title: "Title"
    output:
      pdf_document
    header-includes:
      - \usepackage{LobsterTwo}
    ---
    
    # Header One  
    
    ## Header Two
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
    

    enter image description here

    Not a perfect solution, as it relies on the existence of a TeX package for that font, but still...