5

I have a qmd Quarto file with different output formats, html and pdf.

My goal is, to generate graphics in dependence of the output format.

How can I detect in an R cell, if the processing output format is html or pdf? A simple if statement would be sufficient.

---
title: My title 
format:
  html:
    toc: true
    toc-depth: 3
    html-math-method: katex
  pdf:
    keep-tex: true
    toc: true
    number-sections: true
    colorlinks: true
---
shafee
  • 15,566
  • 3
  • 19
  • 47

2 Answers2

5

Using knitr::is_html_output you could do:

---
title: My title 
format:
   html:
    toc: true
    toc-depth: 3
    html-math-method: katex
  pdf:
    keep-tex: true
    toc: true
    number-sections: true
    colorlinks: true
---

```{r}
if (knitr::is_html_output()) {
  print("HTML")
} else {
  print("pdf")
}
```

Which in case of html will give:

enter image description here

and for pdf:

enter image description here

stefan
  • 90,330
  • 6
  • 25
  • 51
1

You can also make use of pandoc divs with the .content-visible or .content-hidden classes along with when-format clause which supports a variety of format and format aliases such as, pdf, latex, html, html:js etc.

See here for details.

---
title: My title
format:
  html:
    toc: true
    toc-depth: 3
    html-math-method: katex
  pdf:
    keep-tex: true
    toc: true
    number-sections: true
    colorlinks: true
---


::: {.content-visible when-format="html"}

```{r}
print("Output for html document")
```

:::



::: {.content-visible when-format="pdf"}

```{r}
print("Output for pdf document")
```

:::

html output


HTML output


pdf output


PDF output


shafee
  • 15,566
  • 3
  • 19
  • 47