Search code examples
pythonrshinyfpdfreticulate

How to use Download Button in shiny with python reticulate?


I'm building a shiny app and I have a "download button" ! I'm also using python from reticulate because I have a script that generate a PDF for me according to the generated charts in the app. The package I'm using to create the pdf is FPDF

Here is my function in R from python that create my pdf

createPdf <- function(path){
     source_python("plots/create_pdf.py")
       pdf <- PDF()
       pdf$alias_nb_pages()
       pdf$add_page()
       pdf$plot_charts_field('farmer', 'region', 'produto')
       pdf$output(path + 'report.pdf', 'F')
   }

and here is my download button output

output$download <- downloadHandler(
     filename = 'report.pdf',
     content = function(file) {
      createPdf (file)
     })

When I call the function the function "createPdf" I need to pass in the argument the path where the pdf will download and the user will choose the directory, but I don't know how to do that. Is it possible to do that? How could I do it?


Solution

  • My problem was that I needed to pass to the python script the path where the pdf would be saved. Here is my solution to the problem:

    ui.R

    sidebarLayout
      (
        sidebarPanel(width = 3,
          radioButtons(inputId = "choices", "Tipo", c("Individual", "Global"), selected = "Individual"),
          uiOutput("Filters"), downloadButton('download', "Download")
        )
    

    server.R

      makePdf <- function(filename){
         source_python("plots/create_pdf.py")
         if (input$choices == 'Individual')
         {
           pdf <- PDF()
           pdf$alias_nb_pages()
           pdf$add_page()
           pdf$plot_charts_field('farmer', 'region', 'produto')
           pdf$output(filename, 'F')
         } else
         {
           source_python("plots/plot_mapa.py")
           plot_mapa(alltables_filter())
           pdf <- PDF()
           pdf$alias_nb_pages()
           pdf$add_page()
           pdf$plot_charts_global()
           pdf$output(filename, 'F')
         }
       }
    
    
    output$download <- downloadHandler('report.pdf', function(theFile) {
    
           makePdf(theFile)
    
         })
    

    This way, the user can dowload the pdf