Unable to download formatted text, table in different formats such as 'PDF', 'HTML', 'Word', "csv", "tsv" using downloadHandler in ShinyApp code

...
Hello!
I am getting stuck with the 'downloadHandler()' function.

The script below is a ShinyApp small test where

  1. FIRST PRIORITY

I would like to

  • download a formatted text in a word document (.docx) without losing the text style/layout used.
  • download a table in different file format such as .txt (comma delimited or tab delimited file), .pdf, .word , excel file.
  • download a plot in a .pdf, .word, .png file.

The script I wrote was able to display all the format options to choose and the the download button but when I select each of the formats and I click download, It opens a 'Save File' window with a 'DownloadData' name in the File name tab without the user's selected extension. Moreover nothing happens after clicking save the file named DownloadData.

I am developing the ShinyApp using RStudio on Windows but once it is done, It will run on a Linux system too.
Is the ShinyApp script written like below for downloading reports interchangeable between Windows and Linux?

Many thanks in advance for all precious help!!

# Load library
library(shiny)
library(rmarkdown)

# Create a data-table to use as input in the ShinyApp 
dat <- data.frame("NGS" = c("WES", "TDS"), "MEITL" = c(6,1), "EATL" = c(3, 2), "IPTCL" = c(4, 3), stringsAsFactors = FALSE)
rownames(dat) <- dat[,1]
dat[,1] <- NULL

# Building ShinyApp TEST

# UI section
ui <- fluidPage(
  titlePanel(p(h1("Test app"),"by", strong("Ter"))),
  theme = shinythemes::shinytheme("slate"),
  sidebarLayout(
    sidebarPanel(
  selectInput('Tumor','Choose tumor type', choices = c('MEITL','EATL','IPTCL')),
  selectInput('Data','Select data',choices = c('WES','TDS')),
  radioButtons('format', 'Document format:', c('PDF', 'HTML', 'Word', "csv", "tsv"), inline = TRUE),
  downloadButton("DownloadData", "Download")
    ),
    mainPanel(
      tabsetPanel(
        tabPanel("Nf of samples",h3(textOutput('Nb_sample'))),
        tabPanel("Table", br(), tableOutput('table'))
      )
    )
  )
)

# SERVER section 
server = function(input, output, session) {
  output$Nb_sample <- renderText({
    paste("The number of", input$Tumor, "with", input$Data, "analysis are", dat[rownames(dat) == input$Data, colnames(dat) == input$Tumor])
    })
  output$table <- renderTable({
    dat
  }, rownames = TRUE)
  
# Download files 
   output$DownloadData <- downloadHandler(
    filename= function(){
      paste('My-report', sep = ".", switch(
        input$format, PDF = 'pdf', HTML = 'html', Word = 'docx', csv = 'txt', tsv = 'txt'
      ))
    }, 
    
    content = function(file){

# download the table 'dat' in comma OR tab delimited format 
# following the example in 'https://github.com/rstudio/shiny-examples/blob/master/039-download-file/server.R'
# Write to a file specified by the 'file' argument 
      write.table(dat, file, sep = switch(input$format, "csv" = ",", 
                       "tsv" = "\t"),
                       row.names = TRUE)

# download the formatted text 'Nb_sample' in word OR pdf 
# OR HTML format 
      rmarkdown::render(Nb_sample, 
              output_format = switch(input$format,
              PDF = pdf_document(), HTML = html_document(), 
              Word = word_document()), 
              output_file = file)

     })
}
shinyApp(ui = ui, server = server)

I haven't checked this all to the last detail but the first significant thing I noticed is that the temp_folder variable does not represent a temporary folder. you use tempfile() , perhaps your meant to use tempdir() ?

Thanks. I tried but doesn't work. Moreover when I rerun the App , I get Warnings error

Warning in file(con, "w") :
  impossible d'ouvrir le fichier 'C:\Users\te..\AppData\Local\Temp\RtmpKwwIXE\file109038e41c73' : No such file or directory
Error in file(con, "w") : impossible d'ouvrir la connexion

Since I would like to solve first the downloadHandler() issue and in order to make the code above (main post) more easy and quick to read, I removed the code related to the Temporary file/directory creation and I add it here below to keep a record and reply to [nirgrahamuk]'s comment.

       # Part of the code aiming to create a temporary file in a 
       # temp directory for the downloaded file.
       # Please help me with that code too. Thanks.

       # Option 1 - part 1
       # Example below comes from : 
       #https://github.com/rstudio/rmarkdown/issues/1451
       # Copy the report file to a temporary directory before 
       #  processing it, in
       # case we don't have write permissions to the current 
       # working dir 

       # Create temp folder with dir.create
       temp_folder <- tempfile()

       onStop(function() {
       cat("Removing Temporary Files and Folders\n")
       unlink(temp_folder, recursive=TRUE)
       #})

       dir.create(temp_folder)

in the Server section

# Download files 
   output$DownloadData <- downloadHandler(
    filename= function(){
      paste('My-report', sep = ".", switch(
        input$format, PDF = 'pdf', HTML = 'html', Word = 'docx', csv = 'txt', tsv = 'txt'
      ))
    }, 
    
    content = function(file){

      # Option 1 - part 2
      # Example below comes from : 
      #https://github.com/rstudio/rmarkdown/issues/1451
      
      # Note that 'filename' here I hope takes the function 
      # filename as defined just before in downloadHandler()       
      
      tempReport <- file.path(temp_folder, "report.Rmd")
      tempTemplate <- file.path(temp_folder, filename)
      file.copy("report.Rmd", tempReport, overwrite = TRUE)
      file.copy(filename, tempTemplate, overwrite = TRUE)
      

# download the table 'dat' in comma OR tab delimited format 
# following the example in 'https://github.com/rstudio/shiny-examples/blob/master/039-download-file/server.R'
# Write to a file specified by the 'file' argument 
      write.table(dat, file, sep = switch(input$format, "csv" = ",", 
                       "tsv" = "\t"),
                       row.names = TRUE)

# download the formatted text 'Nb_sample' in word OR pdf 
# OR HTML format 
      rmarkdown::render(Nb_sample, 
              output_format = switch(input$format,
              PDF = pdf_document(), HTML = html_document(), 
              Word = word_document()), 
              output_file = file)