Search code examples
rhuxtablewebshot

How can I save a huxtable as png file in R


The huxtable package comes with quick_* functions to save outputs such as html (via quick_html), pdf (via quick_pdf) etc.

However, there seems to be no option to directly save to an imgage (e.g. png).


Solution

  • I had this question a while ago and solved it on my own, but thought it may be helpful to others who run into similar challenges.

    Fortunately, the package webshot allows taking screenshots of huxtable outputs saved with quick_html.

    Here's the solution:

    library(magrittr)
    library(huxtable)
    set.seed(1337)
    
    data <- matrix(rnorm(25), 5, 5)
    my_hux <- as_hux(data) %>%
      set_outer_borders(0.4) %>%
      map_background_color(by_rows("grey95", "white")) %>%
      map_text_color(by_quantiles(c(0.1, 0.9), c("red", "black", "green3")))
    
    quick_html(my_hux, file = "ahuxtable.html", open = FALSE)
    # higher zoom increases resolution and image size
    # you may need to run "webshot::install_phantomjs()" for this to work
    webshot::webshot(url = "ahuxtable.html", file = "ahuxtable.png",
                     zoom = 5, selector = "table")
    

    There seems to be a similar question with flextable, which was solved here.