blob: 01ef2bb84e70e30d3cafdbfdfdb9189fe5bc0ee0 [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 Zhu78e61222017-05-24 20:53:35 -040010#' @examples landscape(knitr::kable(head(mtcars), "latex"))
11#'
Hao Zhucc21dc72017-05-20 01:15:25 -040012#' @export
13landscape <- function(kable_input, margin = NULL) {
14 kable_format <- attr(kable_input, "format")
15 if (!kable_format %in% c("html", "latex")) {
16 message("Currently generic markdown table using pandoc is not supported.")
17 return(kable_input)
18 }
19 if (kable_format == "html") {
20 return(kable_input)
21 }
22 if (kable_format == "latex") {
23 return(landscape_latex(kable_input, margin))
24 }
25}
26
27landscape_latex <- function(kable_input, margin) {
28 kable_attrs <- attributes(kable_input)
Hao Zhucc21dc72017-05-20 01:15:25 -040029 out <- paste0(
Hao Zhud2c0f732017-08-26 10:40:14 -040030 "\n\\begin{landscape}",
31 enc2utf8(as.character(kable_input)),
32 "\n\\end{landscape}"
Hao Zhucc21dc72017-05-20 01:15:25 -040033 )
34
35 if (!is.null(margin)) {
36 out <- paste0(
37 "\n\\newgeometry{margin=", margin, "}", out, "\n\\restoregeometry"
38 )
39 }
40 out <- structure(out, format = "latex", class = "knitr_kable")
41 attributes(out) <- kable_attrs
42 attr(out, "landscape") <- TRUE
43 return(out)
44}