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) |
Hao Zhu | b361fb5 | 2019-01-15 12:24:10 -0600 | [diff] [blame] | 10 | #' @param file By default, as_image saves to an temp file, which works for |
| 11 | #' normal rmarkdown. However if you are using things like xaringan, which can't |
| 12 | #' be a standalone html, you can specify this file be the path you need, eg. |
| 13 | #' "img/something.png" |
| 14 | #' |
Hao Zhu | f1873a4 | 2019-01-07 15:57:01 -0500 | [diff] [blame] | 15 | #' @param ... Additional arguments passed to save_kable. |
| 16 | #' |
Jiaxiang Li | e4b24f2 | 2019-04-05 13:38:11 +0800 | [diff] [blame^] | 17 | #' @examples |
| 18 | #' \dontrun{ |
| 19 | #' library(kableExtra) |
Hao Zhu | f1873a4 | 2019-01-07 15:57:01 -0500 | [diff] [blame] | 20 | #' |
Jiaxiang Li | e4b24f2 | 2019-04-05 13:38:11 +0800 | [diff] [blame^] | 21 | #' kable(mtcars, "latex", booktabs = T) %>% |
| 22 | #' kable_styling(latex_options = c("striped", "scale_down")) %>% |
| 23 | #' row_spec(1, color = "red") %>% |
| 24 | #' as_image() |
| 25 | #' } |
Hao Zhu | f1873a4 | 2019-01-07 15:57:01 -0500 | [diff] [blame] | 26 | #' @export |
Hao Zhu | 62f5031 | 2019-01-15 15:19:29 -0600 | [diff] [blame] | 27 | as_image <- function(x, width = NULL, height = NULL, file = NULL, ...) { |
Hao Zhu | f1873a4 | 2019-01-07 15:57:01 -0500 | [diff] [blame] | 28 | if (is.null(width) + is.null(height) == 0) { |
| 29 | message("Both width and height were defined. Use width only by default. ") |
| 30 | height <- NULL |
| 31 | } |
| 32 | |
Hao Zhu | 62f5031 | 2019-01-15 15:19:29 -0600 | [diff] [blame] | 33 | if (is.null(file)) { |
| 34 | temp_png <- tempfile(fileext = ".png") |
| 35 | } else { |
| 36 | temp_png <- file |
| 37 | } |
| 38 | |
| 39 | |
Hao Zhu | f1873a4 | 2019-01-07 15:57:01 -0500 | [diff] [blame] | 40 | temp_img <- save_kable(x = x, file = temp_png, ...) |
| 41 | |
| 42 | img_dpi <- 300 |
| 43 | |
| 44 | if (is.null(width) + is.null(height) <= 1 & is.null(attr(temp_img, "info"))) { |
| 45 | warning("You need to install magick in order to use width/height in ", |
| 46 | "as_image. ") |
| 47 | } else { |
| 48 | if (!is.null(width)) { |
| 49 | img_dpi <- attr(temp_img, "info")$width / width |
| 50 | } |
| 51 | if (!is.null(height)) { |
| 52 | img_dpi <- attr(temp_img, "info")$height / height |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | include_graphics(temp_png, dpi = img_dpi) |
Hao Zhu | f1873a4 | 2019-01-07 15:57:01 -0500 | [diff] [blame] | 57 | } |
| 58 | |
| 59 | |