Search code examples
rshinywordcloud2

Downloading wordcloud2 output as png/jpg on shiny


I am trying to download output from wordcloud2 on shiny. My code is as below:

 library(shiny)
 library(htmlwidgets)
 library(webshot)
      ui <- shinyUI(fluidPage(mainPanel(
            wordcloud2Output("wordcl"),
            downloadButton(outputId = "savecloud"),
            downloadButton(outputId = "savecloud2")
      )))

  server <- shinyServer(function(input, output, session) {
          wordcl <- reactive ({
           wordcloud2(demoFreq, color = "random-light", backgroundColor = "grey")    
    })

        output$wordcl <- renderWordcloud2({  wordcl() })

 ##### SOLUTION 1 #########
   output$savecloud <- downloadHandler(
          filename = "word.png",
          content = function(cloud) {
          file.copy(wordcl(), cloud)
           })
##### SOLUTION 2 ##########
  output$savecloud2 <- downloadHandler(
        saveWidget(wordcl(), file="temp.html", selfcontained = F),
         webshot("temp.html", file = "word2.png",
      cliprect = "viewport")
      )
      })

shinyApp(ui = ui, server = server)

I have tried two styles using downloadhandler as shown in the code but they return empty results.

Any insight on why they downloadhandler doesn't work or redirection on how best to effect the download function will be appreciated.


Solution

  • I managed to make my download work by using an example of download handler function posted on LeafletMaps here: Why is webshot not working with leaflets in R shiny?

    My updated code is as below:

      library(shiny)
      library(htmlwidgets)
      library(webshot)
      library(wordcloud2)
     #webshot::install_phantomjs()
    
    
      ui <- shinyUI(fluidPage(mainPanel(
           wordcloud2Output("wordcl"),
           downloadButton(outputId = "savecloud")
            )))
    
     server <- shinyServer(function(input, output, session) {
              wordcl <- reactive ({
             wordcloud2(demoFreq, color = "random-light", backgroundColor = "grey")
                        })
            output$wordcl <- renderWordcloud2({
                             wordcl()
                                 })   
        output$savecloud <- downloadHandler(
                   filename = paste("wordcloud", '.png', sep=''),
                   content = function(file) {
                   owd <- setwd(tempdir())
                   on.exit(setwd(owd))
                  saveWidget(wordcl(), "temp.html", selfcontained = FALSE)
                  webshot("temp.html", delay =15, file = file, cliprect = "viewport")
                        }) 
              })
    
    shinyApp(ui = ui, server = server)
    

    The solution given on the link seems to combine the solutions I was trying to implement in my original post.

    The only issue is that it does not work when the app is deployed on shiny.io