Home > Enterprise >  screenshot the whole shinydashboard page as pdf by hitting a button
screenshot the whole shinydashboard page as pdf by hitting a button

Time:11-24

Is there a way to print the whole shinydashboard page as pdf by hitting one actionButton() or a downloadButton(). Based on which tab the user is it will print and download the relative page.

# app.R ##
library(shiny)
library(shinydashboard)
library(DT)

dbHeader <- dashboardHeader(
  title = "fr"
)

ui <- dashboardPage(
  dbHeader,
  dashboardSidebar(),
  dashboardBody(

    tags$hr(),
    actionButton("generate", "Generate PDF"),
    
    tabsetPanel(
      id ="tabA",
      type = "tabs",
      tabPanel("Front",icon = icon("accusoft"),
               plotOutput("ir")
               ),
      tabPanel("Data", icon = icon("table"),
               dataTableOutput("iris")
      )
    )
  )
)

server <- function(input, output) {
  output$ir<-renderPlot(
    plot(iris)
  )
  output$iris<-renderDataTable(
    iris
  )
}

shinyApp(ui = ui, server = server)

CodePudding user response:

tada

If we can do things all in the browser, why do we need the Shiny server? pure javascript, 0 line of server code added.

# app.R ##
library(shiny)
library(shinydashboard)
library(DT)

dbHeader <- dashboardHeader(
    title = "fr"
)

ui <- dashboardPage(
    dbHeader,
    dashboardSidebar(),
    dashboardBody(
        tags$script(src = "https://cdnjs.cloudflare.com/ajax/libs/dom-to-image/2.6.0/dom-to-image.min.js"),
        tags$script(src = "https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.4.0/jspdf.umd.min.js"),
        tags$script(HTML(
            '
            window.jsPDF = window.jspdf.jsPDF;
            function capture(){
                domtoimage.toPng(document.querySelector("body"))
                .then(function(dataurl) {
                    var orientation = window.innerHeight >= window.innerWidth ? "portrait" : "landscape";
                    const doc = new jspdf.jsPDF({unit: "px", orientation: orientation, format: [window.innerHeight, window.innerWidth]});
                    doc.addImage(dataurl, "PNG", 0, 0, window.innerWidth, window.innerHeight);
                    doc.save("page.pdf");
                });
            }
            '
        )),
        tags$hr(),
        actionButton("generate", "Generate PDF", onclick="capture()"),
        tabsetPanel(
            id ="tabA",
            type = "tabs",
            tabPanel("Front",icon = icon("accusoft"),
                     plotOutput("ir")
            ),
            tabPanel("Data", icon = icon("table"),
                     dataTableOutput("iris")
            )
        )
    )
)

server <- function(input, output) {
    output$ir<-renderPlot(
        plot(iris)
    )
    output$iris<-renderDataTable(
        iris
    )
}

shinyApp(ui = ui, server = server)

enter image description here

  • Related