Hao Zhu | f1873a4 | 2019-01-07 15:57:01 -0500 | [diff] [blame] | 1 | #' Render the table as an format-independent image and use it in rmarkdown |
| 2 | #' |
| 3 | #' @description This function generates a temporary png file using `save_kable` |
| 4 | #' and then try to put it in an rmarkdown document using |
| 5 | #' `knitr::include_graphics`. |
| 6 | #' |
| 7 | #' @param x kable input. Either HTML or LaTeX |
| 8 | #' @param width Image width in inches. (1 inch = 2.54 cm) |
| 9 | #' @param height Image height in inches. (1 inch = 2.54 cm) |
| 10 | #' @param ... Additional arguments passed to save_kable. |
| 11 | #' |
| 12 | #' |
| 13 | #' @export |
| 14 | as_image <- function(x, width = NULL, height = NULL, |
| 15 | ...) { |
| 16 | if (is.null(width) + is.null(height) == 0) { |
| 17 | message("Both width and height were defined. Use width only by default. ") |
| 18 | height <- NULL |
| 19 | } |
| 20 | |
| 21 | temp_png <- tempfile(fileext = ".png") |
| 22 | temp_img <- save_kable(x = x, file = temp_png, ...) |
| 23 | |
| 24 | img_dpi <- 300 |
| 25 | |
| 26 | if (is.null(width) + is.null(height) <= 1 & is.null(attr(temp_img, "info"))) { |
| 27 | warning("You need to install magick in order to use width/height in ", |
| 28 | "as_image. ") |
| 29 | } else { |
| 30 | if (!is.null(width)) { |
| 31 | img_dpi <- attr(temp_img, "info")$width / width |
| 32 | } |
| 33 | if (!is.null(height)) { |
| 34 | img_dpi <- attr(temp_img, "info")$height / height |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | include_graphics(temp_png, dpi = img_dpi) |
Hao Zhu | f1873a4 | 2019-01-07 15:57:01 -0500 | [diff] [blame] | 39 | } |
| 40 | |
| 41 | |