blob: 918e04bff8969acbda8d90c5594e4fb3832f42fb [file] [log] [blame]
Hao Zhucc21dc72017-05-20 01:15:25 -04001#' Print the table on an isolated landscape page in PDF
2#'
Hao Zhu8f417202017-05-20 16:37:14 -04003#' @description This function will put the table on an single landscape page.
4#' It's useful for wide tables that cann't be printed on a portrait page.
Hao Zhucc21dc72017-05-20 01:15:25 -04005#'
6#' @param kable_input Output of `knitr::kable()` with `format` specified
7#' @param margin Customizable page margin for special needs. Values can be
8#' "1cm", "1in" or similar.
9#'
Hao Zhu9399dcc2020-08-26 17:27:38 -040010#' @examples
11#' \dontrun{
12#' landscape(knitr::kable(head(mtcars), "latex"))
13#' }
Hao Zhu78e61222017-05-24 20:53:35 -040014#'
Hao Zhucc21dc72017-05-20 01:15:25 -040015#' @export
16landscape <- function(kable_input, margin = NULL) {
17 kable_format <- attr(kable_input, "format")
18 if (!kable_format %in% c("html", "latex")) {
Hao Zhu401ebd82018-01-14 17:10:20 -050019 warning("Please specify format in kable. kableExtra can customize either ",
20 "HTML or LaTeX outputs. See https://haozhu233.github.io/kableExtra/ ",
21 "for details.")
Hao Zhucc21dc72017-05-20 01:15:25 -040022 return(kable_input)
23 }
24 if (kable_format == "html") {
25 return(kable_input)
26 }
27 if (kable_format == "latex") {
28 return(landscape_latex(kable_input, margin))
29 }
30}
31
32landscape_latex <- function(kable_input, margin) {
33 kable_attrs <- attributes(kable_input)
Hao Zhucc21dc72017-05-20 01:15:25 -040034 out <- paste0(
Hao Zhud2c0f732017-08-26 10:40:14 -040035 "\n\\begin{landscape}",
Hao Zhu3fc0e882018-04-03 16:06:41 -040036 solve_enc(kable_input),
Hao Zhud2c0f732017-08-26 10:40:14 -040037 "\n\\end{landscape}"
Hao Zhucc21dc72017-05-20 01:15:25 -040038 )
39
40 if (!is.null(margin)) {
41 out <- paste0(
42 "\n\\newgeometry{margin=", margin, "}", out, "\n\\restoregeometry"
43 )
44 }
45 out <- structure(out, format = "latex", class = "knitr_kable")
46 attributes(out) <- kable_attrs
47 attr(out, "landscape") <- TRUE
48 return(out)
49}