Changing fonts in RMarkdown PDFs

Comic from Pinterest

Note: this post has been edited on 2 August 2020 - there was a typo in the indenting of the YAML. Thank you to Henry Hankins for catching this!

Inspiration for this post

After learning how to change the fonts within a graph in R, I wanted to be able to change the fonts in the body of an RMarkdown to match. I specifically wanted to be able to knit an RMarkdown to PDF using the Source Sans Pro Google font, but these instructions should work for any Google font.

Cairo

To embed custom fonts in PDFs, you can use the Cairo graphics library. This library is installed with R, but if you are using a Mac, you do need to install XQuartz. To check if you are able to run Cairo, you can run capabilities():

capabilities()
##        jpeg         png        tiff       tcltk         X11        aqua 
##        TRUE        TRUE        TRUE        TRUE        TRUE        TRUE 
##    http/ftp     sockets      libxml        fifo      cledit       iconv 
##        TRUE        TRUE        TRUE        TRUE       FALSE        TRUE 
##         NLS     profmem       cairo         ICU long.double     libcurl 
##        TRUE        TRUE        TRUE        TRUE        TRUE        TRUE

If cairo shows up as TRUE, you are good to go.

YAML header

To use Cairo to change the font of your RMarkdown pdf, you can modify the YAML heading:

---
title: "New fancy font!"
header-includes:
   - \usepackage[default]{sourcesanspro}
   - \usepackage[T1]{fontenc}
mainfont: SourceSansPro
output:
  pdf_document
---

The \usepackage components of the header load Latex packages for your font (I am using Source Sans Pro in this example).

Chunk options

The final step to use the font in your knitted pdf is to set the graphical device to Cairo in your code chunk option. At the beginning of your RMarkdown, the first chunk should include code that looks something like this:

knitr::opts_chunk$set(echo = TRUE)

Add dev="cairo_pdf" as one of the arguments:

knitr::opts_chunk$set(echo = TRUE, dev="cairo_pdf")

You can read more about other chunk options here.

Avatar
Cecina Babich Morrow
Compass PhD Program

My research interests range from harnessing data to improve mental healthcare to understanding global patterns of macroecology.

comments powered by Disqus

Related