Hao Zhu | cc21dc7 | 2017-05-20 01:15:25 -0400 | [diff] [blame] | 1 | #' Print the table on an isolated landscape page in PDF |
| 2 | #' |
Hao Zhu | 8f41720 | 2017-05-20 16:37:14 -0400 | [diff] [blame] | 3 | #' @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 Zhu | cc21dc7 | 2017-05-20 01:15:25 -0400 | [diff] [blame] | 5 | #' |
| 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 Zhu | 78e6122 | 2017-05-24 20:53:35 -0400 | [diff] [blame] | 10 | #' @examples landscape(knitr::kable(head(mtcars), "latex")) |
| 11 | #' |
Hao Zhu | cc21dc7 | 2017-05-20 01:15:25 -0400 | [diff] [blame] | 12 | #' @export |
| 13 | landscape <- function(kable_input, margin = NULL) { |
| 14 | kable_format <- attr(kable_input, "format") |
| 15 | if (!kable_format %in% c("html", "latex")) { |
Hao Zhu | 401ebd8 | 2018-01-14 17:10:20 -0500 | [diff] [blame] | 16 | warning("Please specify format in kable. kableExtra can customize either ", |
| 17 | "HTML or LaTeX outputs. See https://haozhu233.github.io/kableExtra/ ", |
| 18 | "for details.") |
Hao Zhu | cc21dc7 | 2017-05-20 01:15:25 -0400 | [diff] [blame] | 19 | return(kable_input) |
| 20 | } |
| 21 | if (kable_format == "html") { |
| 22 | return(kable_input) |
| 23 | } |
| 24 | if (kable_format == "latex") { |
| 25 | return(landscape_latex(kable_input, margin)) |
| 26 | } |
| 27 | } |
| 28 | |
| 29 | landscape_latex <- function(kable_input, margin) { |
| 30 | kable_attrs <- attributes(kable_input) |
Hao Zhu | cc21dc7 | 2017-05-20 01:15:25 -0400 | [diff] [blame] | 31 | out <- paste0( |
Hao Zhu | d2c0f73 | 2017-08-26 10:40:14 -0400 | [diff] [blame] | 32 | "\n\\begin{landscape}", |
| 33 | enc2utf8(as.character(kable_input)), |
| 34 | "\n\\end{landscape}" |
Hao Zhu | cc21dc7 | 2017-05-20 01:15:25 -0400 | [diff] [blame] | 35 | ) |
| 36 | |
| 37 | if (!is.null(margin)) { |
| 38 | out <- paste0( |
| 39 | "\n\\newgeometry{margin=", margin, "}", out, "\n\\restoregeometry" |
| 40 | ) |
| 41 | } |
| 42 | out <- structure(out, format = "latex", class = "knitr_kable") |
| 43 | attributes(out) <- kable_attrs |
| 44 | attr(out, "landscape") <- TRUE |
| 45 | return(out) |
| 46 | } |