blob: 5a5cbc08f5623fc63cd418e44db1a7b79bebfb15 [file] [log] [blame]
Hao Zhu73cf3732018-05-11 17:50:05 -04001#' Save kable to files
2#'
3#' @param x A piece of HTML code for tables, usually generated by kable and
4#' kableExtra
Hao Zhu7f8b6842018-10-23 17:41:13 -04005#' @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 Zhu73cf3732018-05-11 17:50:05 -04009#' @param bs_theme Which Bootstrap theme to use
10#' @param self_contained Will the files be self-contained?
Hao Zhu7f8b6842018-10-23 17:41:13 -040011#' @param ... Additional variables being passed to `webshot::webshot`.`
Hao Zhu73cf3732018-05-11 17:50:05 -040012#'
13#' @export
14save_kable <- function(x, file,
Hao Zhu7f8b6842018-10-23 17:41:13 -040015 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
22save_kable_html <- function(x, file, bs_theme, self_contained, ...) {
Hao Zhu73cf3732018-05-11 17:50:05 -040023 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 Zhu7f8b6842018-10-23 17:41:13 -040030
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 Zhu73cf3732018-05-11 17:50:05 -040037 unlink("lib", recursive = TRUE)
Hao Zhu7f8b6842018-10-23 17:41:13 -040038 } 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 Zhu73cf3732018-05-11 17:50:05 -040044 }
45}
Hao Zhu7f8b6842018-10-23 17:41:13 -040046
47save_kable_latex <- function(x, file) {
48
49}