Add An Export Module to Shiny-app for Highcharts Figure
Highcharts is the best JavaScript chart library, I feel. By default, there is an export button which can let you save the interactive figure to PNG, JPEG, PDF and SVG format, and one important point is, you can use it in your shiny app through R package rCharts. However, there are some limits in such a way, the default exporting engine is based http, so if your shiny-app’s portal is https, then you can’t use the exporting feature (It seems Highcharts has also a https based export engine). I have spent a lot of time to configure a Highcharts export server, it works internally, but not outside. I can’t figure out the problem, but found another solution.
The figures created by Highcharts are actually SVG element in HTML, we can easily extract that element using JavaScript, and fill it into a textInput of Shiny, when textInput received the SVG element, its value changed, so it triggered Shiny server to response, then we can let Shiny-server to save the SVG element onto our server. We can convert that SVG file into the format we want, and download it use downloadHandler.
The most difficult parts to R users which are not familiar with JavaScript and Linux are:
###1. Extract the SVG element and fill it to textInput.
We can bind this function to a button: when clicking that button, web browser will extract the SVG element, fill it into an textInput using JavaScript and tell Shiny-server that the textInput got a new value. After receiving that textInput’s value has changed, Shiny-server will save its value to a SVG file.
###2. Convert SVG file to other formats under Linux. There are several programs can convert svg file to other formats, I choose inkscape. To install it, run this command:
After installing it on your server, we can call it through R using system command:
That’s it!
We can also add an option to change the dimension of the figure:
And to export the figure data is even simple:
where p$data
was assign before. Here is a demo, and you can find the source code on my gist.