blob: fa71b8a0be676a5c8e9eb470c282e67a530a1571 [file] [log] [blame]
Hao Zhu8902df82019-01-07 16:27:32 -05001---
2title: "Save Tables and Use them as Images"
3author: "Hao"
4date: "1/7/2019"
5output: html_document
6---
7
8Before `kableExtra` 1.0, we have a function called `kable_as_image`, which can transform a LaTeX tables to an image and include it in an rmarkdown document. Starting from `kableExtra` 1.0, we will split this function into two pieces: `save_kable` and `as_image`. `save_kable` will save any LaTeX and **HTML** tables to any format (`html`, `png`, `jpg`, `pdf` etc.). The output format will be defined by the file extension of the output file name. Here are a few examples.
9
10```{r, eval=FALSE}
11# not evaluating
12library(kableExtra)
13
14kable(mtcars[1:5, ], "html") %>%
15 kable_styling("striped") %>%
16 row_spec(1, color = "red") %>%
17 save_kable("inst/test.pdf")
18
19kable(mtcars, "latex") %>%
20 kable_styling(latex_options = "striped") %>%
21 save_kable("inst/test.png")
22```
23
24# Picturizing Tables for cross-formating support
25`kableExtra` only supports `HTML` and `LaTeX`. One way to get it work with `Word` is to render the table `as_image`. This example below shows you how to render a LaTeX table in HTML document.
26```{r}
27library(kableExtra)
28
29kable(mtcars, "latex", booktabs = T) %>%
30 kable_styling(latex_options = c("striped", "scale_down")) %>%
31 row_spec(1, color = "red") %>%
32 as_image()
33```
34
35You can also specify either `width` or `height` of the image. The image will be scaled properly.
36
37```{r}
38kable(mtcars, "latex", booktabs = T) %>%
39 kable_styling(latex_options = c("striped", "scale_down")) %>%
40 row_spec(1, color = "red") %>%
41 as_image(width = 8)
42```
43
44`as_image` also works for HTML tables. Of course, it is only meaning to do so if you want a HTML bootstrap style table in PDF/Word.
45```{r}
46kable(mtcars, "html") %>%
47 kable_styling("striped") %>%
48 row_spec(1, color = "red") %>%
49 as_image(width = 2)
50```
51
52One problem with this method, especially if you are using it in `Word`, is that to the end, the product you made is a picture. Please make sure your reader be aware that they cannot select/edit the table.