dreamRs / apexcharter

:bar_chart: R Htmlwidget for ApexCharts.js
https://dreamrs.github.io/apexcharter
Other
138 stars 15 forks source link

Save as png #22

Closed Alik-V closed 3 years ago

Alik-V commented 3 years ago

Hi Victor,

I hope you have been well. Is there any way to save an apexchart as an image?

Best, Alik

pvictor commented 3 years ago

Hello Alik,

Do you think of something other than the button above the graphs? There is a method to get the image in base64 from which you can generate a PNG, it may work in Shiny. What's your use-case?

Victor

Alik-V commented 3 years ago

Hi Victor,

I am trying to generate a powerpoint report through rmarkdown in shiny after a user has adjusted data on apexchart graphs through the shiny app. So far I tried webshot2 package which works just fine locally, but inevitably crashes when tried on in the app published on rstudio-connect server (which has something to do with Chromote dependency I think).

Best, Alik

pvictor commented 3 years ago

Hello Alik,

Install latest version from GitHub, then you can retrieve chart's base64 dataURI and write a PNG like this:

library(shiny)
library(apexcharter)

ui <- fluidPage(
  fluidRow(
    column(
      width = 8, offset = 2,
      tags$h2("Export PNG"),
      actionButton("redraw", "Redraw chart"),
      apexchartOutput("chart"),
      downloadButton("download", "Download PNG"),
      verbatimTextOutput("result"),
      uiOutput(outputId = "image")
    )
  )
)

server <- function(input, output, session) {

  output$chart <- renderApexchart({
    input$redraw
    apexchart() %>%
      ax_chart(type = "bar") %>%
      ax_series(
        list(
          name = "Example",
          data = sample(1:100, 5)
        )
      ) %>%
      ax_xaxis(
        categories = LETTERS[1:5]
      ) %>% 
      set_input_export("export")
  })

  output$result <- renderPrint({
    input$export
  })

  output$download <- downloadHandler(
    filename = function() {
      "apexcharts.png"
    },
    content = function(file) {
      img <- input$export$imgURI
      raw <- base64enc::base64decode(what = gsub("data:image/png;base64,", "", img, fixed = TRUE))
      png::writePNG(png::readPNG(raw), file)
    }
  )

  output$image <- renderUI({
    tags$img(src = input$export)
  })

}

if (interactive())
  shinyApp(ui, server)

Victor

Alik-V commented 3 years ago

That's fantastic, thanks a lot Victor!