blob: 43ddadd3143d50719900b935722aacbdc5a6acf1 [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
Hao Zhu7039ecf2019-01-06 17:51:21 -05007#' conversion.
Hao Zhu73cf3732018-05-11 17:50:05 -04008#' @param bs_theme Which Bootstrap theme to use
9#' @param self_contained Will the files be self-contained?
Hao Zhu7039ecf2019-01-06 17:51:21 -050010#' @param extra_dependencies Additional HTML dependencies. For example,
11#' `list(`
12#' @param ... Additional variables being passed to `webshot::webshot`. This
13#' is for HTML only.
14#' @param latex_header_includes A character vector of extra LaTeX header stuff.
15#' Each element is a row. You can have things like
16#' `c("\\\\usepackage{threeparttable}", "\\\\usepackage{icons}")` You could
17#' probably add your language package here if you use non-English text in your
18#' table, such as `\\\\usepackage[magyar]{babel}`.
19#' @param keep_tex A T/F option to control if the latex file that is initially created
20#' should be kept. Default is `FALSE`.
Hao Zhuab670942020-08-19 15:35:35 -040021#' @param density density argument passed to magick if needed. Default is 300.
Jiaxiang Lie4b24f22019-04-05 13:38:11 +080022#' @examples
23#' \dontrun{
24#' library(kableExtra)
Hao Zhu73cf3732018-05-11 17:50:05 -040025#'
Jiaxiang Lie4b24f22019-04-05 13:38:11 +080026#' kable(mtcars[1:5, ], "html") %>%
27#' kable_styling("striped") %>%
28#' row_spec(1, color = "red") %>%
29#' save_kable("inst/test.pdf")
30#' }
Hao Zhu73cf3732018-05-11 17:50:05 -040031#' @export
32save_kable <- function(x, file,
Hao Zhu7039ecf2019-01-06 17:51:21 -050033 bs_theme = "simplex", self_contained = TRUE,
34 extra_dependencies = NULL, ...,
Hao Zhuab670942020-08-19 15:35:35 -040035 latex_header_includes = NULL, keep_tex = FALSE,
36 density = 300) {
Hao Zhud8516932019-01-06 18:56:47 -050037 if (!is.null(attr(x, "format")) && attr(x, "format") == "latex") {
Hao Zhuab670942020-08-19 15:35:35 -040038 return(save_kable_latex(x, file, latex_header_includes, keep_tex, density))
Hao Zhu7f8b6842018-10-23 17:41:13 -040039 }
Hao Zhu7039ecf2019-01-06 17:51:21 -050040 return(save_kable_html(x, file, bs_theme, self_contained,
Hao Zhuab670942020-08-19 15:35:35 -040041 extra_dependencies, density, ...))
Hao Zhu7f8b6842018-10-23 17:41:13 -040042}
43
Hao Zhu7039ecf2019-01-06 17:51:21 -050044save_kable_html <- function(x, file, bs_theme, self_contained,
Hao Zhuab670942020-08-19 15:35:35 -040045 extra_dependencies, density, ...) {
Hao Zhu7039ecf2019-01-06 17:51:21 -050046 dependencies <- list(
Hao Zhu73cf3732018-05-11 17:50:05 -040047 rmarkdown::html_dependency_jquery(),
48 rmarkdown::html_dependency_bootstrap(theme = bs_theme),
Hao Zhuab670942020-08-19 15:35:35 -040049 html_dependency_lightable(),
Hao Zhu73cf3732018-05-11 17:50:05 -040050 html_dependency_kePrint()
51 )
Hao Zhu7039ecf2019-01-06 17:51:21 -050052 if (!is.null(extra_dependencies)) {
53 dependencies <- append(dependencies, extra_dependencies)
54 }
55
Hao Zhu46a42a12019-01-22 00:11:11 -050056 html_header <- htmltools::tags$head(dependencies)
Hao Zhu73cf3732018-05-11 17:50:05 -040057 html_table <- htmltools::HTML(as.character(x))
58 html_result <- htmltools::tagList(html_header, html_table)
Hao Zhu7f8b6842018-10-23 17:41:13 -040059
ghaarsma8e786ad2019-02-16 21:28:01 -060060
61 # Check if we are generating an image and use webshot to do that
Hao Zhu7f8b6842018-10-23 17:41:13 -040062 if (tools::file_ext(file) %in% c("png", "jpg", "jpeg", "pdf")) {
ghaarsma8e786ad2019-02-16 21:28:01 -060063 file_temp_html <- tempfile(pattern = tools::file_path_sans_ext(file), tmpdir = '.', fileext = ".html")
64
65 file.create(file_temp_html)
66 file_temp_html <- normalizePath(file_temp_html)
67 file.create(file)
68 file <- normalizePath(file)
69
70 # Generate a random temp lib directory. The sub is to remove any back or forward slash at the beginning of the temp_dir
71 temp_dir <- sub(pattern = '^[\\\\/]{1,2}', replacement = '', tempfile(pattern = 'lib', tmpdir = '' , fileext = ''))
72 htmltools::save_html(html_result, file = file_temp_html, libdir = temp_dir)
73
74 result <- webshot::webshot(file_temp_html, file, ...)
75 if (is.null(result)) {
76 # A webshot could not be created. Delete newly created files and issue msg
77 file.remove(file)
78 file.remove(file_temp_html)
79 message('save_kable could not create image with webshot package. Please check for any webshot messages')
Hao Zhuf1873a42019-01-07 15:57:01 -050080 } else {
ghaarsma8e786ad2019-02-16 21:28:01 -060081 if (tools::file_ext(file) == "pdf") {
82 message("Note that HTML color may not be displayed on PDF properly.")
83 }
84 # Remove temp html file and temp lib directory
85 file.remove(file_temp_html)
86 unlink(file.path(dirname(file_temp_html), temp_dir), recursive = TRUE)
87
88 if (requireNamespace("magick", quietly = TRUE)) {
Hao Zhuab670942020-08-19 15:35:35 -040089 img_rework <- magick::image_read(file, density = density)
ghaarsma8e786ad2019-02-16 21:28:01 -060090 img_rework <- magick::image_trim(img_rework)
91 img_info <- magick::image_info(img_rework)
Hao Zhuab670942020-08-19 15:35:35 -040092 magick::image_write(img_rework, file, density = density)
ghaarsma8e786ad2019-02-16 21:28:01 -060093 attr(file, "info") <- img_info
94 } else {
95 message("save_kable will have the best result with magick installed. ")
96 }
Hao Zhuf1873a42019-01-07 15:57:01 -050097 }
ghaarsma8e786ad2019-02-16 21:28:01 -060098
Hao Zhu7f8b6842018-10-23 17:41:13 -040099 } else {
Hao Zhuf1873a42019-01-07 15:57:01 -0500100 file.create(file)
101 file <- normalizePath(file)
ghaarsma8e786ad2019-02-16 21:28:01 -0600102
Hao Zhu7f8b6842018-10-23 17:41:13 -0400103 if (self_contained) {
ghaarsma8e786ad2019-02-16 21:28:01 -0600104 # Generate a random temp lib directory. The sub is to remove any back or forward slash at the beginning of the temp_dir
105 temp_dir <- sub(pattern = '^[\\\\/]{1,2}', replacement = '', tempfile(pattern = 'lib', tmpdir = '' , fileext = ''))
106 htmltools::save_html(html_result, file = file, libdir = temp_dir)
107 #remove_html_doc(file)
Hao Zhu7f8b6842018-10-23 17:41:13 -0400108 rmarkdown::pandoc_self_contained_html(file, file)
ghaarsma8e786ad2019-02-16 21:28:01 -0600109 unlink(file.path(dirname(file), temp_dir), recursive = TRUE)
110 } else {
111 # Simply use the htmltools::save_html to write out the files. Dependencies go to the standard lib folder
112 htmltools::save_html(html_result, file = file)
Hao Zhu7f8b6842018-10-23 17:41:13 -0400113 }
Hao Zhu73cf3732018-05-11 17:50:05 -0400114 }
Hao Zhud8516932019-01-06 18:56:47 -0500115
Hao Zhuf1873a42019-01-07 15:57:01 -0500116 return(invisible(file))
Hao Zhu73cf3732018-05-11 17:50:05 -0400117}
Hao Zhu7f8b6842018-10-23 17:41:13 -0400118
Hao Zhu46a42a12019-01-22 00:11:11 -0500119remove_html_doc <- function(x){
120 out <- paste(readLines(x)[-1], collapse = "\n")
121 writeLines(out, x)
122}
123
Hao Zhuab670942020-08-19 15:35:35 -0400124save_kable_latex <- function(x, file, latex_header_includes, keep_tex, density) {
Hao Zhu7039ecf2019-01-06 17:51:21 -0500125 temp_tex <- c(
126 "\\documentclass[border=1mm, preview]{standalone}",
127 "\\usepackage[active,tightpage]{preview}",
128 "\\usepackage{varwidth}",
129 "\\usepackage{amssymb, amsmath}",
130 "\\usepackage{ifxetex,ifluatex}",
131 "\\usepackage{fixltx2e}",
132 "\\usepackage{polyglossia}",
Hao Zhu7039ecf2019-01-06 17:51:21 -0500133 latex_pkg_list(),
134 "\\usepackage{graphicx}",
Hao Zhu7039ecf2019-01-06 17:51:21 -0500135 "\\usepackage{xltxtra,xunicode}",
Hao Zhueac7b032020-08-19 14:07:03 -0400136 "\\usepackage{xcolor}",
Hao Zhu7039ecf2019-01-06 17:51:21 -0500137 latex_header_includes,
138 "\\begin{document}",
139 solve_enc(x),
140 "\\end{document}"
141 )
142 temp_tex <- paste(temp_tex, collapse = "\n")
Hao Zhu7f8b6842018-10-23 17:41:13 -0400143
Hao Zhud8516932019-01-06 18:56:47 -0500144 temp_tex_file <- paste0(tools::file_path_sans_ext(file), ".tex")
Hao Zhu7039ecf2019-01-06 17:51:21 -0500145 writeLines(temp_tex, temp_tex_file, useBytes = T)
Hao Zhuf1873a42019-01-07 15:57:01 -0500146 temp_tex_file <- normalizePath(temp_tex_file)
147 file_no_ext <- tools::file_path_sans_ext(temp_tex_file)
148
149 owd <- setwd(dirname(temp_tex_file))
150
AC Craft7cea5332020-04-19 16:01:07 -0400151 system(paste0('xelatex -interaction=batchmode "', temp_tex_file,'"'))
Hao Zhu7039ecf2019-01-06 17:51:21 -0500152 if (!keep_tex) {
Hao Zhuf1873a42019-01-07 15:57:01 -0500153 temp_file_delete <- paste0(file_no_ext, c(".tex", ".aux", ".log"))
Hao Zhu7039ecf2019-01-06 17:51:21 -0500154 unlink(temp_file_delete)
155 }
156
Hao Zhuf1873a42019-01-07 15:57:01 -0500157 table_img_info <- NULL
Hao Zhud8516932019-01-06 18:56:47 -0500158 if (tools::file_ext(file) != "pdf") {
159 table_img_pdf <- try(
Hao Zhuf1873a42019-01-07 15:57:01 -0500160 magick::image_read(paste0(file_no_ext, ".pdf"),
Hao Zhuab670942020-08-19 15:35:35 -0400161 density = density), silent = T)
Hao Zhud8516932019-01-06 18:56:47 -0500162 if (class(table_img_pdf) == "try-error") {
163 stop("We hit an error when trying to use magick to read the generated ",
Hao Zhu53e59612019-01-15 12:16:06 -0600164 "PDF file. You may check your magick installation and try to ",
165 "use magick::image_read to read the PDF file manually. It's also ",
166 "possible that you didn't have ghostscript installed.")
Hao Zhud8516932019-01-06 18:56:47 -0500167 }
Hao Zhuf1873a42019-01-07 15:57:01 -0500168 unlink(paste0(file_no_ext, ".pdf"))
Hao Zhud8516932019-01-06 18:56:47 -0500169 table_img <- magick::image_convert(table_img_pdf,
170 tools::file_ext(file))
Hao Zhuf1873a42019-01-07 15:57:01 -0500171 table_img_info <- magick::image_info(table_img)
172 magick::image_write(table_img,
Hao Zhuab670942020-08-19 15:35:35 -0400173 paste0(file_no_ext, ".", tools::file_ext(file)),
174 density = density)
Hao Zhu7039ecf2019-01-06 17:51:21 -0500175 }
Hao Zhu7039ecf2019-01-06 17:51:21 -0500176
Hao Zhuf1873a42019-01-07 15:57:01 -0500177 setwd(owd)
178
179 out <- paste0(file_no_ext, ".", tools::file_ext(file))
180 attr(out, "info") <- table_img_info
181 return(invisible(out))
Hao Zhu7f8b6842018-10-23 17:41:13 -0400182}