blob: 35e805a5f0718f9b894e3580cfd2cc2139b89b2f [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 Zhu73cf3732018-05-11 17:50:05 -040021#'
22#' @export
23save_kable <- function(x, file,
Hao Zhu7039ecf2019-01-06 17:51:21 -050024 bs_theme = "simplex", self_contained = TRUE,
25 extra_dependencies = NULL, ...,
26 latex_header_includes = NULL, keep_tex = FALSE) {
Hao Zhud8516932019-01-06 18:56:47 -050027 if (!is.null(attr(x, "format")) && attr(x, "format") == "latex") {
Hao Zhu7039ecf2019-01-06 17:51:21 -050028 return(save_kable_latex(x, file, latex_header_includes, keep_tex))
Hao Zhu7f8b6842018-10-23 17:41:13 -040029 }
Hao Zhu7039ecf2019-01-06 17:51:21 -050030 return(save_kable_html(x, file, bs_theme, self_contained,
31 extra_dependencies, ...))
Hao Zhu7f8b6842018-10-23 17:41:13 -040032}
33
Hao Zhu7039ecf2019-01-06 17:51:21 -050034save_kable_html <- function(x, file, bs_theme, self_contained,
35 extra_dependencies, ...) {
36 dependencies <- list(
Hao Zhu73cf3732018-05-11 17:50:05 -040037 rmarkdown::html_dependency_jquery(),
38 rmarkdown::html_dependency_bootstrap(theme = bs_theme),
39 html_dependency_kePrint()
40 )
Hao Zhu7039ecf2019-01-06 17:51:21 -050041 if (!is.null(extra_dependencies)) {
42 dependencies <- append(dependencies, extra_dependencies)
43 }
44
Hao Zhu46a42a12019-01-22 00:11:11 -050045 html_header <- htmltools::tags$head(dependencies)
Hao Zhu73cf3732018-05-11 17:50:05 -040046 html_table <- htmltools::HTML(as.character(x))
47 html_result <- htmltools::tagList(html_header, html_table)
Hao Zhu7f8b6842018-10-23 17:41:13 -040048
ghaarsma8e786ad2019-02-16 21:28:01 -060049
50 # Check if we are generating an image and use webshot to do that
Hao Zhu7f8b6842018-10-23 17:41:13 -040051 if (tools::file_ext(file) %in% c("png", "jpg", "jpeg", "pdf")) {
ghaarsma8e786ad2019-02-16 21:28:01 -060052 file_temp_html <- tempfile(pattern = tools::file_path_sans_ext(file), tmpdir = '.', fileext = ".html")
53
54 file.create(file_temp_html)
55 file_temp_html <- normalizePath(file_temp_html)
56 file.create(file)
57 file <- normalizePath(file)
58
59 # Generate a random temp lib directory. The sub is to remove any back or forward slash at the beginning of the temp_dir
60 temp_dir <- sub(pattern = '^[\\\\/]{1,2}', replacement = '', tempfile(pattern = 'lib', tmpdir = '' , fileext = ''))
61 htmltools::save_html(html_result, file = file_temp_html, libdir = temp_dir)
62
63 result <- webshot::webshot(file_temp_html, file, ...)
64 if (is.null(result)) {
65 # A webshot could not be created. Delete newly created files and issue msg
66 file.remove(file)
67 file.remove(file_temp_html)
68 message('save_kable could not create image with webshot package. Please check for any webshot messages')
Hao Zhuf1873a42019-01-07 15:57:01 -050069 } else {
ghaarsma8e786ad2019-02-16 21:28:01 -060070 if (tools::file_ext(file) == "pdf") {
71 message("Note that HTML color may not be displayed on PDF properly.")
72 }
73 # Remove temp html file and temp lib directory
74 file.remove(file_temp_html)
75 unlink(file.path(dirname(file_temp_html), temp_dir), recursive = TRUE)
76
77 if (requireNamespace("magick", quietly = TRUE)) {
78 img_rework <- magick::image_read(file)
79 img_rework <- magick::image_trim(img_rework)
80 img_info <- magick::image_info(img_rework)
81 magick::image_write(img_rework, file)
82 attr(file, "info") <- img_info
83 } else {
84 message("save_kable will have the best result with magick installed. ")
85 }
Hao Zhuf1873a42019-01-07 15:57:01 -050086 }
ghaarsma8e786ad2019-02-16 21:28:01 -060087
Hao Zhu7f8b6842018-10-23 17:41:13 -040088 } else {
Hao Zhuf1873a42019-01-07 15:57:01 -050089 file.create(file)
90 file <- normalizePath(file)
ghaarsma8e786ad2019-02-16 21:28:01 -060091
Hao Zhu7f8b6842018-10-23 17:41:13 -040092 if (self_contained) {
ghaarsma8e786ad2019-02-16 21:28:01 -060093 # Generate a random temp lib directory. The sub is to remove any back or forward slash at the beginning of the temp_dir
94 temp_dir <- sub(pattern = '^[\\\\/]{1,2}', replacement = '', tempfile(pattern = 'lib', tmpdir = '' , fileext = ''))
95 htmltools::save_html(html_result, file = file, libdir = temp_dir)
96 #remove_html_doc(file)
Hao Zhu7f8b6842018-10-23 17:41:13 -040097 rmarkdown::pandoc_self_contained_html(file, file)
ghaarsma8e786ad2019-02-16 21:28:01 -060098 unlink(file.path(dirname(file), temp_dir), recursive = TRUE)
99 } else {
100 # Simply use the htmltools::save_html to write out the files. Dependencies go to the standard lib folder
101 htmltools::save_html(html_result, file = file)
Hao Zhu7f8b6842018-10-23 17:41:13 -0400102 }
Hao Zhu73cf3732018-05-11 17:50:05 -0400103 }
Hao Zhud8516932019-01-06 18:56:47 -0500104
Hao Zhuf1873a42019-01-07 15:57:01 -0500105 return(invisible(file))
Hao Zhu73cf3732018-05-11 17:50:05 -0400106}
Hao Zhu7f8b6842018-10-23 17:41:13 -0400107
Hao Zhu46a42a12019-01-22 00:11:11 -0500108remove_html_doc <- function(x){
109 out <- paste(readLines(x)[-1], collapse = "\n")
110 writeLines(out, x)
111}
112
Hao Zhu7039ecf2019-01-06 17:51:21 -0500113save_kable_latex <- function(x, file, latex_header_includes, keep_tex) {
114 temp_tex <- c(
115 "\\documentclass[border=1mm, preview]{standalone}",
116 "\\usepackage[active,tightpage]{preview}",
117 "\\usepackage{varwidth}",
118 "\\usepackage{amssymb, amsmath}",
119 "\\usepackage{ifxetex,ifluatex}",
120 "\\usepackage{fixltx2e}",
121 "\\usepackage{polyglossia}",
Hao Zhu7039ecf2019-01-06 17:51:21 -0500122 latex_pkg_list(),
123 "\\usepackage{graphicx}",
Hao Zhu7039ecf2019-01-06 17:51:21 -0500124 "\\usepackage{xltxtra,xunicode}",
125 latex_header_includes,
126 "\\begin{document}",
127 solve_enc(x),
128 "\\end{document}"
129 )
130 temp_tex <- paste(temp_tex, collapse = "\n")
Hao Zhu7f8b6842018-10-23 17:41:13 -0400131
Hao Zhud8516932019-01-06 18:56:47 -0500132 temp_tex_file <- paste0(tools::file_path_sans_ext(file), ".tex")
Hao Zhu7039ecf2019-01-06 17:51:21 -0500133 writeLines(temp_tex, temp_tex_file, useBytes = T)
Hao Zhuf1873a42019-01-07 15:57:01 -0500134 temp_tex_file <- normalizePath(temp_tex_file)
135 file_no_ext <- tools::file_path_sans_ext(temp_tex_file)
136
137 owd <- setwd(dirname(temp_tex_file))
138
Hao Zhu8902df82019-01-07 16:27:32 -0500139 system(paste0("xelatex -interaction=batchmode ", temp_tex_file))
Hao Zhu7039ecf2019-01-06 17:51:21 -0500140 if (!keep_tex) {
Hao Zhuf1873a42019-01-07 15:57:01 -0500141 temp_file_delete <- paste0(file_no_ext, c(".tex", ".aux", ".log"))
Hao Zhu7039ecf2019-01-06 17:51:21 -0500142 unlink(temp_file_delete)
143 }
144
Hao Zhuf1873a42019-01-07 15:57:01 -0500145 table_img_info <- NULL
Hao Zhud8516932019-01-06 18:56:47 -0500146 if (tools::file_ext(file) != "pdf") {
147 table_img_pdf <- try(
Hao Zhuf1873a42019-01-07 15:57:01 -0500148 magick::image_read(paste0(file_no_ext, ".pdf"),
Hao Zhud8516932019-01-06 18:56:47 -0500149 density = 300), silent = T)
150 if (class(table_img_pdf) == "try-error") {
151 stop("We hit an error when trying to use magick to read the generated ",
Hao Zhu53e59612019-01-15 12:16:06 -0600152 "PDF file. You may check your magick installation and try to ",
153 "use magick::image_read to read the PDF file manually. It's also ",
154 "possible that you didn't have ghostscript installed.")
Hao Zhud8516932019-01-06 18:56:47 -0500155 }
Hao Zhuf1873a42019-01-07 15:57:01 -0500156 unlink(paste0(file_no_ext, ".pdf"))
Hao Zhud8516932019-01-06 18:56:47 -0500157 table_img <- magick::image_convert(table_img_pdf,
158 tools::file_ext(file))
Hao Zhuf1873a42019-01-07 15:57:01 -0500159 table_img_info <- magick::image_info(table_img)
160 magick::image_write(table_img,
161 paste0(file_no_ext, ".", tools::file_ext(file)))
Hao Zhu7039ecf2019-01-06 17:51:21 -0500162 }
Hao Zhu7039ecf2019-01-06 17:51:21 -0500163
Hao Zhuf1873a42019-01-07 15:57:01 -0500164 setwd(owd)
165
166 out <- paste0(file_no_ext, ".", tools::file_ext(file))
167 attr(out, "info") <- table_img_info
168 return(invisible(out))
Hao Zhu7f8b6842018-10-23 17:41:13 -0400169}