R/embed_htmlwidget.R

#' Embeds widget in the rmarkdown document.
#'
#' @author Krzysztof Jedrzejewski <kjedrz@gmail.com>
#' @param widget A htmlwidget to be embedded.
#' @param rasterise Whether the widget should be rasterised, even if it may be included in the interactive form. Maybe useful when given widget isn't properly embedded in document types it should be.
#' @return Htmlwidget given as paramater or no value (but the widget is transformed correctly to be embedded in the PDF document).
#' @description
#' Converts htmlwidgets to a form that may be correctly embedded in the output document, depending on its type.
#' Requires `webshot` and `EBImage` packages.\cr
#'
#' You may install `webshot` using following code:\cr
#' \code{
#' devtools::install_github("wch/webshot")\cr
#' webshot::install_phantomjs()
#' }\cr
#'
#' You may install `EBImage` using following code:
#' \code{
#' source("https://bioconductor.org/biocLite.R")\cr
#' biocLite("EBImage")
#' }
#' @examples
#' library(htmlwidgets)
#' library(wordcloud2)
#' w = wordcloud2(demoFreq, size = 1, shape = 'star')
#' embed_htmlwidget(w)
#' @export
embed_htmlwidget <- function(widget, rasterise = F) {
  outputFormat = knitr::opts_knit$get("rmarkdown.pandoc.to")
  if(rasterise || outputFormat == 'latex') {
    html.file = tempfile("tp",fileext=".html")
    png.file = tempfile("tp",fileext=".png")

    htmlwidgets::saveWidget(widget, html.file, selfcontained = FALSE)
    webshot::webshot(html.file, file = png.file, cliprect = "viewport")
    img = EBImage::readImage(png.file)

    EBImage::display(img)
  } else {
    widget
  }
}
kjedrzejewski/rmarkdown.helpers documentation built on May 20, 2019, 10:25 a.m.