File: landscape.R

package info (click to toggle)
r-cran-kableextra 1.4.0%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,400 kB
  • sloc: javascript: 579; makefile: 2
file content (53 lines) | stat: -rw-r--r-- 1,619 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#' Print the table on an isolated landscape page in PDF
#'
#' @description This function will put the table on an single landscape page.
#' It's useful for wide tables that can't be printed on a portrait page.
#'
#' @param kable_input Output of `knitr::kable()` with `format` specified
#' @param margin Customizable page margin for special needs. Values can be
#' "1cm", "1in" or similar.
#'
#' @examples
#' \dontrun{
#' landscape(knitr::kable(head(mtcars), "latex"))
#' }
#'
#' @export
landscape <- function(kable_input, margin = NULL) {
  kable_format <- attr(kable_input, "format")
  if (kable_format %in% c("pipe", "markdown")) {
    kable_input <- md_table_parser(kable_input)
    kable_format <- attr(kable_input, "format")
  }
  if (!kable_format %in% c("html", "latex")) {
    warning("Please specify format in kable. kableExtra can customize either ",
            "HTML or LaTeX outputs. See https://haozhu233.github.io/kableExtra/ ",
            "for details.")
    return(kable_input)
  }
  if (kable_format == "html") {
    return(kable_input)
  }
  if (kable_format == "latex") {
    return(landscape_latex(kable_input, margin))
  }
}

landscape_latex <- function(kable_input, margin) {
  kable_attrs <- attributes(kable_input)
  out <- paste0(
    "\n\\begin{landscape}",
    solve_enc(kable_input),
    "\n\\end{landscape}"
  )

  if (!is.null(margin)) {
    out <- paste0(
      "\n\\newgeometry{margin=", margin, "}", out, "\n\\restoregeometry"
    )
  }
  out <- structure(out, format = "latex", class = "knitr_kable")
  attributes(out) <- kable_attrs
  attr(out, "landscape") <- TRUE
  return(out)
}