6

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
---
0

2 Answers 2

6

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

Sign up to request clarification or add additional context in comments.

Comments

4

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


Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.