5

How can I print the current page in R shiny web applications? It is possible in HTML by using the command of window.print();. But I could not find and implement its correspondent R Shiny command. What is on my mind is something like the following? How can I call an html command in SERVER?

actionButton("print", "PRINT")

server <- function(input, output) {

        observeEvent(input$print, {
          window.print();
        })
}
BRCN
  • 635
  • 1
  • 12
  • 26

1 Answers1

12

This can be done using shinyjs package to call a js function.

library(shiny)
library(shinyjs)

jsCode <- 'shinyjs.winprint = function(){
window.print();
}'

ui <- shinyUI(fluidPage(
  useShinyjs(),
  extendShinyjs(text = jsCode, functions = c("winprint")),
  actionButton("print", "PRINT")
  ))



server <- shinyServer(function(input, output) {
  
  observeEvent(input$print, {
    js$winprint()
   })
})


shinyApp(ui, server)
Nimantha
  • 6,405
  • 6
  • 28
  • 69
SBista
  • 7,479
  • 1
  • 27
  • 58
  • 1
    Wouldn't the result be identical to just using the browser's native "Print page" command? – rvrvrv Jun 25 '20 at 11:16
  • 2
    Yes @rvrvrv. That was the requirement as per the question asked. – SBista Jun 25 '20 at 13:52
  • Ok thanks, I'm trying to find a way to print the page while preserving all graphs (browser's in-built Print cuts things off) so was wondering whether this might have solved my problem! – rvrvrv Jun 25 '20 at 16:10
  • This solution no longer works. Error: shinyjs: extendShinyjs: `functions` argument must be provided – SportSci Sep 12 '20 at 17:18
  • Updated `functions = c("winprint")` in `extendShinyjs()` to make it work. – YBS Sep 12 '20 at 20:30