Specifying transparent color in HTML and PDF output

依然范特西╮ 提交于 2020-11-28 16:01:15

问题


In an R markdown report rendered to both PDF and HTML, I would like to colorize text with different transparencies.
For example, I would like to use the same orange with 3 different alpha values (0.3, 0.6, 1.0).

Nicholas Hamilton provides a function to color text regardless of the output format (PDF/latex or HTML). An updated MWE of the fct. was provided by Mark Neal.

To work with transparent colors, the colFmt() function needs to be adapted somehow as far as I see.

What I tried

gplots::col2hex(color) allows converting color names to hex RGB strings, which can then be used in colFmt(). Unfortunately, the function does not allow for transparencies.

palr::col2hex(color) allows for conversion with transparencies. For PDF output these are "ignored" by colFmt() (the transparency values are simply added as text). For HTML output, they do not resemble the transparent version of the provided color (see figure below)

PDF output of MWE

HTML output of MWE

MWE

---
title: "Colored text with transparency"
author: "Test"
output: html_document
#output: pdf_document
header-includes:
  \usepackage[usenames,dvipsnames]{xcolor}
---

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

## Define colorizing function

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

## Apply colorizing function

### gplots

```{r include=FALSE}
library(gplots) # to be able to use col2hex() to convert color names to hex RGB strings
hex_color <- str_remove(gplots::col2hex(color),"#") # convert color names to hex RGB strings
```
Some `r colFmt("orange text",hex_color)` 

### palr
```{r include=FALSE}
library(palr) # for col2hex() 
hex_color <- str_remove(palr::col2hex(color),"#")
hex_color_light <- str_remove(palr::col2hex(color, alpha = 0.3),"#")
```
Some `r colFmt("orange text",hex_color)` and some `r colFmt("light orange text", hex_color_light)` 

来源:https://stackoverflow.com/questions/64694618/specifying-transparent-color-in-html-and-pdf-output

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