| Hao Zhu | 73cf373 | 2018-05-11 17:50:05 -0400 | [diff] [blame] | 1 | #' Save kable to files | 
 | 2 | #' | 
 | 3 | #' @param x A piece of HTML code for tables, usually generated by kable and | 
 | 4 | #' kableExtra | 
| Hao Zhu | 7f8b684 | 2018-10-23 17:41:13 -0400 | [diff] [blame] | 5 | #' @param file save to files. If the input table is in HTML and the output file | 
 | 6 | #' ends with `.png`, `.pdf` and `.jpeg`, `webshot` will be used to do the | 
 | 7 | #' conversion | 
 | 8 | #' | 
| Hao Zhu | 73cf373 | 2018-05-11 17:50:05 -0400 | [diff] [blame] | 9 | #' @param bs_theme Which Bootstrap theme to use | 
 | 10 | #' @param self_contained Will the files be self-contained? | 
| Hao Zhu | 7f8b684 | 2018-10-23 17:41:13 -0400 | [diff] [blame] | 11 | #' @param ... Additional variables being passed to `webshot::webshot`.` | 
| Hao Zhu | 73cf373 | 2018-05-11 17:50:05 -0400 | [diff] [blame] | 12 | #' | 
 | 13 | #' @export | 
 | 14 | save_kable <- function(x, file, | 
| Hao Zhu | 7f8b684 | 2018-10-23 17:41:13 -0400 | [diff] [blame] | 15 |                        bs_theme = "simplex", self_contained = TRUE, ...) { | 
 | 16 |   if (attr(x, "format") == "latex") { | 
 | 17 |     return(save_kable_latex(x, file)) | 
 | 18 |   } | 
 | 19 |   return(save_kable_html(x, file, bs_theme, self_contained, ...)) | 
 | 20 | } | 
 | 21 |  | 
 | 22 | save_kable_html <- function(x, file, bs_theme, self_contained, ...) { | 
| Hao Zhu | 73cf373 | 2018-05-11 17:50:05 -0400 | [diff] [blame] | 23 |   html_header <- htmltools::tags$head( | 
 | 24 |     rmarkdown::html_dependency_jquery(), | 
 | 25 |     rmarkdown::html_dependency_bootstrap(theme = bs_theme), | 
 | 26 |     html_dependency_kePrint() | 
 | 27 |   ) | 
 | 28 |   html_table <- htmltools::HTML(as.character(x)) | 
 | 29 |   html_result <- htmltools::tagList(html_header, html_table) | 
| Hao Zhu | 7f8b684 | 2018-10-23 17:41:13 -0400 | [diff] [blame] | 30 |  | 
 | 31 |   # Use webshot if necessary | 
 | 32 |   if (tools::file_ext(file) %in% c("png", "jpg", "jpeg", "pdf")) { | 
 | 33 |     file_html <- paste0(tools::file_path_sans_ext(file), ".html") | 
 | 34 |     htmltools::save_html(html_result, file = file_html) | 
 | 35 |     webshot::webshot(file_html, file, ...) | 
 | 36 |     unlink(file_html) | 
| Hao Zhu | 73cf373 | 2018-05-11 17:50:05 -0400 | [diff] [blame] | 37 |     unlink("lib", recursive = TRUE) | 
| Hao Zhu | 7f8b684 | 2018-10-23 17:41:13 -0400 | [diff] [blame] | 38 |   } else { | 
 | 39 |     htmltools::save_html(html_result, file = file) | 
 | 40 |     if (self_contained) { | 
 | 41 |       rmarkdown::pandoc_self_contained_html(file, file) | 
 | 42 |       unlink("lib", recursive = TRUE) | 
 | 43 |     } | 
| Hao Zhu | 73cf373 | 2018-05-11 17:50:05 -0400 | [diff] [blame] | 44 |   } | 
 | 45 | } | 
| Hao Zhu | 7f8b684 | 2018-10-23 17:41:13 -0400 | [diff] [blame] | 46 |  | 
 | 47 | save_kable_latex <- function(x, file) { | 
 | 48 |  | 
 | 49 | } |