Specifying colour in HTML and PDF output

两盒软妹~` 提交于 2021-01-29 02:30:41

问题


An answer by Nicholas Hamilton specifies how to use colour text in PDF and HTML output from Markdown using an R expression.

If I create an RMarkdown document, I get no joy, Warning message is

Error in colFmt("MY RED TEXT", "red") : object 'opts_knit' not found Calls: ... inline_exec -> hook_eval -> withVisible -> eval -> eval -> colFmt Execution halted

What am I missing?

Copy and paste of RMarkdown below:

---
title: "test colour"
author: "mbn"
output: html_document
---

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

## R Markdown

This is an R Markdown document. 

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

## Test colour now

`r colFmt("MY RED TEXT",'red')`

回答1:


Change opts_knit$get to knitr::opts_knit$get and your code should work.

See https://stat.ethz.ch/R-manual/R-devel/library/base/html/ns-dblcolon.html




回答2:


Here is an example of an rmarkdown code that is self contained and works, and uses hex colour ids to give consistent colours across pdf and html. Thanks to contributions from Kenji for pointing out I needed knitr library.

---
title: "test colour"
author: "mbn"
output: html_document
#output: pdf_document
header-includes:
  \usepackage[usenames,dvipsnames]{xcolor}
---

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

```

## R Markdown

This is an R Markdown document. 

```{r cars}
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
}
```

## Test colour now

`r colFmt("My colored text favorite green latex/pdf and html",'7ac143')`


来源:https://stackoverflow.com/questions/55233763/specifying-colour-in-html-and-pdf-output

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!