blob: f545bb512cc885aa6f74919fff8fb56d8f4eebda [file] [log] [blame]
---
title: "Save Tables and Use them as Images"
author: "Hao"
date: "1/7/2019"
output: html_document
---
Before `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.
```{r, eval=FALSE}
# not evaluating
library(kableExtra)
kable(mtcars[1:5, ], "html") %>%
kable_styling("striped") %>%
row_spec(1, color = "red") %>%
save_kable("inst/test.pdf")
kable(mtcars, "latex") %>%
kable_styling(latex_options = "striped") %>%
save_kable("inst/test.png")
```
# Feature Dependencies
To get it work, you need to make sure you have the following things installed.
```{r, eval = F}
install.packages("magick")
install.packages("webshot")
webshot::install_phantomjs()
```
In the end, please make sure you can use `magick::read_image()` function properly for a PDF. On some system (not only windows), it's possible that GhostScript was not setup properly so even if you have `magick` installed, `magick::read_image()` still cannot read PDF properly. That said, although `save_kable` and `as_image` provide really attractive feature, they may not work on every computer.
# Turn your tables into images for cross-formating support
`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. Same rules applies when you use them in `rmarkdown::word_document`.
```{r}
library(kableExtra)
kable(mtcars, "latex", booktabs = T) %>%
kable_styling(latex_options = c("striped", "scale_down")) %>%
row_spec(1, color = "red") %>%
as_image()
```
You can also specify either `width` or `height` of the image. The image will be scaled properly. The units are in inches.
```{r}
kable(mtcars, "latex", booktabs = T) %>%
kable_styling(latex_options = c("striped", "scale_down")) %>%
row_spec(1, color = "red") %>%
as_image(width = 8)
```
`as_image` also works for HTML tables. It means that you can also put in a bootstrap flavored table (image) in Word or PDF.
```{r}
kable(mtcars, "html") %>%
kable_styling("striped") %>%
row_spec(1, color = "red") %>%
as_image(width = 4)
```
Note that, by default, as_image saves to an temp file, which works for normal rmarkdown. However if you are using things like xaringan, which can't be a standalone html, you can specify the `file` option in `as_image` be the path you need, eg. "img/something.png"