Search code examples
rpdftextcolorsr-markdown

How to color element of text in RMarkdown for a pdf file


I am trying to color in red a part of a text for a pdf file

---
output: pdf_document
---

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


## *Title*


Text <p style="color:red">text to color </p>

Unfortunately, this does not return the wanted output.I have read a post, suggesting to use this function I reported below the way I arranged it (source: Specifying transparent color in HTML and PDF output),

---
output: pdf_document
---

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


```{r colFmt}
colFmt = function(x,color){
  outputFormat = opts_knit$get("rmarkdown.pandoc.to")
  if(outputFormat == 'latex')
    paste("\\textcolor[HTML]{",color,"}{",x,"}",sep="")
  else if(outputFormat == 'html')
    paste("<font color='",color,"'>",x,"</font>",sep="")
  else
    x
}
```

text `r colFmt("text to color",hex_color)` 

but since it does not return the wanted output I am quite confused on how this should be used.

Can anyone provde some help? Thanks


Solution

  • Using latex to style pdf

    ---
    title: "Untitled"
    output:
      pdf_document: default
    date: "2023-09-23"
    ---
    
    ```{r setup, include=FALSE}
    knitr::opts_chunk$set(echo = TRUE)
    
    
    
    \textcolor{red}{text to color}