Knitting R notebooks with iframe tags instead of embed?

49 views Asked by At

Since last year (at least), Safari has been very unreliable in rendering PDFs plots in R Markdown HTML notebooks. The notebook HTML files are interpreted with an empty gray box where the PDF plot should be. This issue is caused because rmarkdown and knitr use the <embed> tag to include the PDF plots in the HTML file.

Safari does not have issues displaying PDFs embedded with <iframe>. Therefore, I'm looking for a way to knit R notebooks using <iframe> instead of <embed> to embed PDFs. Is this possible with knitr or rmarkdown?

As of now, I have to manually find and replace the <embed> tags with <iframe> after knitting my notebooks or use a different browser just for R notebooks.

For reference, I'm using {r, dev="cairo_pdf"} chunk options when I want the output to be a PDF.

1

There are 1 answers

0
Ricardo A. On

After some digging, I found a solution that solves this issue. It's a modification of the knitr::knit_hooks that finds and replaces embed with iframe when the user requests a PDF plot output.

# Include this code in the setup chunk of your R notebook
library(knitr)
knit_hooks$set(plot = function(x, options) {
  # Check if the output format is pdf
  if (options$dev == "cairo_pdf") {
    gsub("embed", "iframe", hook_plot_html(x, options))
  } else {
    # Default behavior for other output formats
    hook_plot_html(x, options)
  }
})

I've been using R notebooks for years, but I never knew you could have so much control of the chunk outputs using hooks. That's pretty neat.

Hopefully, a Knitr power user will post a more elegant solution here. Meanwhile, I hope this helps someone with a similar problem - I've been dealing with this issue for over a year on two different computers and have yet to find a mention of this problem elsewhere.