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.
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.
We love it when R users help each other, but RStudio does not monitor or answer the comments in this thread. If you'd like to get specific help, we recommend the RStudio Community as well as the Shiny Discussion Forum for in depth discussion of Shiny related questions and How to get help article for a list of the best ways to get help with R code.comments powered by Disqus