我正在尝试打印活动的tabPanel,使其显示在屏幕上,同时带有闪亮的打印按钮。 tabPanel可以包含各种图表和数据表。
我在下面做了一个可复制的例子,下面的代码有问题 打印时数据表丢失其格式,并且 打印时无法对齐中心。
library(shiny)
library(ggplot2) # for the diamonds dataset
library(shinyjs)
library(DT)
library(dplyr)
jsCode <- "shinyjs.winprint = function(){
var mywindow = window.open('', 'PRINT', 'height=400,width=600');
mywindow.document.write('</head><body >');
mywindow.document.write(document.getElementsByClassName('tab-pane active')[0].innerHTML);
mywindow.document.write('</body></html>');
mywindow.print();
mywindow.close();
return true;
}"
ui <- fluidPage(
title = "Examples of DataTables",
sidebarLayout(
sidebarPanel(
conditionalPanel(
'input.dataset === "diamonds"',
checkboxGroupInput("show_vars", "Columns in diamonds to show:",
names(diamonds), selected = names(diamonds))
),
conditionalPanel(
'input.dataset === "mtcars"',
helpText("Click the column header to sort a column.")
),
conditionalPanel(
'input.dataset === "iris"',
helpText("Display 5 records by default.")
),
useShinyjs(),
extendShinyjs(text = jsCode),
actionButton("print", "PRINT")
),
mainPanel(
tabsetPanel(
id = 'dataset',
tabPanel("diamonds", DT::dataTableOutput("mytable1"),
plotOutput("plot1")),
tabPanel("mtcars", DT::dataTableOutput("mytable2")),
tabPanel("iris", DT::dataTableOutput("mytable3"))
)
)
)
)
server <- function(input, output) {
# choose columns to display
diamonds2 = diamonds[sample(nrow(diamonds), 1000), ]
output$mytable1 <- DT::renderDataTable(
DT::datatable(diamonds2[diamonds2$color %in% c("H","D"), input$show_vars, drop = FALSE]) %>%
DT::formatStyle("color", target = "row",
backgroundColor = styleEqual(c("H", "D"), c('red', 'white')))
)
output$plot1 <- renderPlot({
plot(cars, type="p")
})
# sorted columns are colored now because CSS are attached to them
output$mytable2 <- DT::renderDataTable({
DT::datatable(mtcars, options = list(orderClasses = TRUE))
})
# customize the length drop-down menu; display 5 rows per page by default
output$mytable3 <- DT::renderDataTable({
DT::datatable(iris, options = list(lengthMenu = c(5, 30, 50), pageLength = 5))
})
observeEvent(input$print, {
js$winprint()
})
}
shinyApp(ui, server)