Home > Enterprise >  How to create a custom example environment for r markdown pdf output?
How to create a custom example environment for r markdown pdf output?

Time:04-30

I am hoping to create a custom-styled example environment within r markdown that renders pdf output.

I want something that looks like

But I would want the example to be styled and numbered. Maybe put inside a block that look maybe like this (Image from

CodePudding user response:

You could use tcolorbox for the example:

---
header-includes: |
   \BeforeBeginEnvironment{document}{
      \usepackage[most]{tcolorbox}
      \let\example\undefined 
      \let\endexample\undefined 
      \newtcolorbox[auto counter]{example}{
        colback=white,
        colbacktitle=black,
        arc=0mm,
        title={Example~\thetcbcounter:},
        bottom=-.7\baselineskip,
        colframe=black,
        fonttitle=\bfseries
   }}
urlcolor: blue
extension: latex_macros
numbersections: true
output:
   bookdown::pdf_document2:
      toc: false
      keep_tex: true
biblio-style: apalike
---

test

```{example} 
Hello  
```

enter image description here

CodePudding user response:

You can use some packages as for ordinary LaTeX. I give you an example with the packages thmtools and mdframed.

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

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

## R Markdown

\begin{example}
    Hello I am an example.
\end{example}

File preamble.tex:

\usepackage{amsthm,thmtools}
\usepackage{mdframed}

\definecolor{verylightgray}{gray}{0.9}

\declaretheoremstyle[
  headfont=\color{black}\normalfont\bfseries,
  bodyfont=\color{black}\normalfont\sffamily,
  mdframed={
    backgroundcolor=verylightgray, 
    hidealllines=true, 
    innertopmargin=2pt, 
    innerbottommargin=2pt, 
    skipabove=\topsep, 
    skipbelow=\topsep
  }]{mystyle} 

\declaretheorem[
  style=mystyle,
  name=Example
]{example}

enter image description here

A linebreak or a top margin is needed...

  • Related