gulhamster
gulhamster

Reputation: 21

R Markdown PDF Change Font & Color for Headers

I need to update the color and font of the header (only header) in a R Markdown PDF file. I have found recourses on how to do this for the whole document, but can't find an answer for changing the headers only.

Thank you kindly!

---
title: "Untitled"
output: pdf_document
---

Upvotes: 0

Views: 6842

Answers (2)

Ralf Stubner
Ralf Stubner

Reputation: 26823

Simplified version of the solution provided by Grada Gukovic:

You can add simple LaTeX statements to your document via the YAML header header-includes, e.g.:

---
title: "Untitled"
output: pdf_document
header-includes:
    - \usepackage{sectsty}
    - \allsectionsfont{\color{cyan}}
---

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

## R Markdown

This is an R Markdown document. Markdown is a simple formatting syntax for
authoring HTML, PDF, and MS Word documents. For more details on using
R Markdown see <http://rmarkdown.rstudio.com>.

Result:

enter image description here

This is most useful for small additions like the one seen here. If you want to add more than a few lines of LaTeX code it is often easier to save them to an external file, say preamble.tex and include that via

---
output:
  pdf_document:
    includes:
      in_header: preamble.tex
---

Other possible places are before_body and after_body, c.f. ?rmarkdown::includes.

Upvotes: 7

Grada Gukovic
Grada Gukovic

Reputation: 1253

There is no option to do this in rmarkdown::pdf_document. You can do this by modifying the .tex template being used using the sectsty package for latex. For example the following changes the color of all headers to cyan:

  1. Download the default latex template from here: tex template

  2. Open the template in Notepad and add the following lines on an appropriate place in the document preamble(I have them as lines nr. 200 and 201):

    \usepackage{sectsty}
    \allsectionsfont{\color{cyan}}
  1. Save the modified file with the extension .tex (my file is called "Cyansections.tex") and put it in R's working directory.

  2. Modify the header of the .rmd document:

---
title: "Untitled"
output: 
    pdf_document:
        template: Cyansections.tex
---

If you want a different color or font consult this answer

and sectsty's manual Especially section 4 of the manual for chanhing fonts

Upvotes: 4

Related Questions