Generating downloadable reports
By: Winston Chang
After interacting with a Shiny application and getting it certain state, your users may want to download a report in HTML or PDF format. You can easily add the ability to generate a report with knitr and rmarkdown at the click of a button.
There are two key parts for this:
downloadHandler()which knits the document on demand and passes values to the document.
- An R Markdown document which is parameterized.
This app takes one input value, and passes it as a parameter to an .Rmd document, which is rendered (or knitted) into an HTML output file. You can see this app in action here.
Note that due to an issue in the rmarkdown package, the default value of a parameter in the YAML header cannot be
NULL, so we’ve used
NA as the default value of
rmarkdown::render() function has many options to control the processing and output. See the rmarkdown website to learn more. Some commonly used options are described below.
By default, an HTML file generated by
rmarkdown::render() will have all plots and other images embedded directly in the HTML, so you can simply publish or send the HTML file, without needing to handle separate image files.
If you want PDF output, the
rmarkdown::render() function can do that. This will require two changes:
- Change the
output: pdf_documentin the YAML header of the Rmd file.
It will also require pdflatex to be installed on your system.
Another way to generate a PDF is to pass in a value to
output_format argument of
rmarkdown::render(), as demonstrated in this app.
To generate a Microsoft Word document:
- Change the
output: word_documentin the YAML header of the Rmd file.
rmarkdown::render, it is possible for the Rmd document to directly access variables that are available to the Shiny app, including input values like
input$slider. This can be done by using the default value for
envir (instead of passing in a new environment). However, we recommend passing in
params and using a new
envir, because it provides better code isolation and makes things easier to debug.
If you have questions about this article or would like to discuss ideas presented here, please post on RStudio Community. Our developers monitor these forums and answer questions periodically. See help for more help with all things Shiny.