7.8 Embed arbitrary files in the HTML output file
As mentioned in Section 7.7, we can embed a copy of the Rmd source document in the HTML output file. Sometimes the Rmd source file alone may not be enough to reproduce the report. For example, the report may need an external data file. There is a series of functions in the xfun package (Xie 2020g) that enable you to embed arbitrary files in the HTML output file. To use these functions, make sure you have the following R packages available:
xfun::pkg_load2(c("htmltools", "mime"))
Then you can use one of the functions xfun::embed_file()
, xfun::embed_files()
, or xfun::embed_dir()
in an R code chunk to embed one or multiple files or an entire directory in the HTML output, e.g.,
```{r echo=FALSE}
# a single file
xfun::embed_file('source.Rmd')
# multiple files
xfun::embed_files(c('source.Rmd', 'data.csv'))
# a directory
xfun::embed_dir('data/', text = 'Download full data')
```
You can also provide the list of files programmatically, e.g.,
# embed all Rmd and csv files
xfun::embed_files(list.files(".", "[.](Rmd|csv)$"))
For multiple files, they are first compressed to a zip file, and the zip file will be embedded. These functions return a link, on which a reader can click on the HTML page to download the embedded file.
You can learn more technical details behind these functions from the help page ?xfun::embed_file
or the blog post at https://yihui.org/en/2018/07/embed-file/. Based on the same idea, the downloadthis package (Mattioni Maturana 2020) has implemented download buttons, so that users can click buttons to download files instead of links. If you prefer using buttons, you may consider using this package.
References
Mattioni Maturana, Felipe. 2020. Downloadthis: Implement Download Buttons in Rmarkdown. https://github.com/fmmattioni/downloadthis.
———. 2020g. Xfun: Miscellaneous Functions by Yihui Xie. https://github.com/yihui/xfun.