1

How to add background colors to specific section of the text while creating PDF reports using rmarkdown. Something like below

click here for image

i tried something like this but it is working in latex but not in rmarkdown

\titleformat{\section}{\sffamily\Large\bfseries\rlap{\color{DarkGreen!90}\rule[-0.5ex]{\linewidth}{3ex}\vspace{-3ex}}\sffamily\Large\color{white}}{\thesection}{1em}{}

this is how it looks in latex

this is in rmarkdown

---
title: "Untitled"
output: pdf_document
header-includes:
- \usepackage{amsfonts,amssymb,amsmath}
- \usepackage[table, svgnames]{xcolor}
- \usepackage{titlesec}
- \usepackage{sectsty}
- \usepackage{xcolor, soul}  
- \sectionfont{\color{red}}
- \subsectionfont{\color{green}}
- \subsubsectionfont{\color{blue}}
- \titleformat{\section}{\sffamily\Large\bfseries\rlap{\color{DarkGreen!90}\rule[-0.5ex]{\linewidth}{3ex}\vspace{-3ex}}\sffamily\Large\color{white}}{\thesection}{1em}{}

---
\section{Highlights}
# Section

1 Answers1

0

Two problems:

  • rmarkdown already loads xcolor without paying attention to the options you need. As a workaround you could trick markdown by passing the necessary options to all packages

  • sectsty will destroy all changes you do via titlesec. Don't load them both


---
title: "Untitled"
output: 
  pdf_document:
    keep_tex: true
classoption: svgnames
header-includes:
- \usepackage{amsfonts,amssymb,amsmath}
- \usepackage{titlesec}
- \usepackage{soul}  
- \titleformat{\section}{\sffamily\Large\bfseries\rlap{\color{DarkGreen!90}\rule[-1.5ex]{\linewidth}{3ex}\vspace{-3.5ex}}\sffamily\Large\color{white}}{\thesection}{1em}{}

---
\section{Highlights}
# Section

enter image description here