5

I would like to include a mermaid diagram in a PDF generated with R markdown.

According to this post, mermaid creates an HTML widget as output. Unfortunately, the answer provided there for xaringan slides does not work for PDFs generated in R markdown.

A Rmd-MWE is below. Any help is greatly appreciated!

---
title: "DiagrammeR: mermaid diagram in Rmd"
output: pdf_document
---

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

# Simple mermaid diagram

```{r}
library(DiagrammeR)
mermaid("
graph LR
    A-->B
    ", height = '100%', width = '100%')
```
mavericks
  • 1,005
  • 17
  • 42
  • Updating to latest `knitr` and installing `webshot` as suggested by @pwtw solves the issue! See [info on HTML widgets used in non-HTML output formats](https://bookdown.org/yihui/bookdown/html-widgets.html) "Before knitr v1.13, you will get an error when you render HTML widgets to an output format that is not HTML. Since knitr v1.13, HTML widgets will be rendered automatically as screenshots taken via the `webshot` package (Chang 2019" – mavericks Oct 27 '20 at 10:15

2 Answers2

3

Run these two lines in your Rstudio console:

install.packages('webshot')
webshot::install_phantomjs()

https://bookdown.org/yihui/bookdown/html-widgets.html

pwtw
  • 46
  • 2
1

Here is a workaround. Replace the code in your last chunk with this:

library(DiagrammeR)
library(networkD3)
library(webshot)

g  <- mermaid("
graph LR
    A-->B
    ", height = '100%', width = '100%')

saveNetwork(g, "g.html")


webshot("g.html", "g.png", vheight = 50)
gd047
  • 29,749
  • 18
  • 107
  • 146
  • Thank you for your suggestion. If feasible, a solution without any additional storing and loading of files would be preferred. – mavericks Feb 27 '20 at 10:30
  • 2
    Also, if I run your code, the HTML generated with `saveNetwork` contains the mermaid graph, the png file produced with `webshot` however is empty. – mavericks Feb 27 '20 at 11:02