Downloading wordcloud2 output as png/jpg on shiny

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-20 06:19:35

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/54260164/downloading-wordcloud2-output-as-png-jpg-on-shiny

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!