【发布时间】:2018-08-10 16:32:15
【问题描述】:
我制作了一个闪亮的应用程序,其中有人上传文件,计算了一些比率,并且可以使用阈值滑块来格式化这些比率。我为此使用DT::formatStyle,它工作得非常好。据我了解这个函数,它创建一个回调来处理条件格式。
然后,我想使用DT 中的按钮扩展名导出数据。我想在导出为 pdf 或打印时保留格式。事实证明这是行不通的:数据在没有任何格式的情况下被导出。我试过设置exportOptions(list(stripHtml = FALSE)),还是不行。
令我惊讶的是,即使我直接从 Firefox 打印(作为文件/打印...但保持字体粗细。我怀疑我可能需要调整 CSS,但我不知道该怎么做。
我想有一种方法可以“按原样”制作 pdf 和/或打印,最接近我在浏览器中看到的内容。 下面是一个例子:
library(shiny)
library(DT)
library(dplyr)
data("starwars")
ui <- fluidPage(title = "Ratios",
sidebarLayout(
sidebarPanel(width = 2,
actionButton("button", "Go"), # Emulates data loading
sliderInput("seuil_j", "Threshold J",
min = 0, max = 80, value = 35, step = 0.5)),
mainPanel(
fluidRow(column(width = 12,
DT::dataTableOutput("ratios"))))
)
)
server <- function(input, output, session) {
donnees_ratios <- reactive({
req(input$button)
set.seed(14)
starwars %>%
select(1:10) %>% # DataTables is not happy with list columns
mutate(signe = sample(c(1, -1), replace = TRUE, size = nrow(.)),
ratio_j = signe * mass / height) %>%
select(name, mass, height, signe, ratio_j, everything())
})
output$ratios <- DT::renderDataTable({
donnees_ratios() %>%
creer_DT() %>%
formatter_DT(input)
})
}
creer_DT <- function(donnees) {
datatable(donnees,
rownames = FALSE,
class = 'cell-border stripe compact hover',
extensions = c("Buttons"),
options = list(
dom = 'Blfrtip',
buttons = list(
list(extend = "pdf",
exportOptions = list(stripHtml = FALSE,
columns = ':visible'),
orientation = 'landscape'),
list(extend = "print",
exportOptions = list(stripHtml = FALSE,
columns = ':visible')),
"excel", "csv", "colvis"),
language = list(
decimal = ",",
thousands = " " # small unbreakable space
)
)
)
}
formatter_DT <- function(table, input) {
table %>%
formatPercentage(columns = c("ratio_j"),
digits = 1L, dec.mark = ",", mark = " ") %>%
formatRound(columns = c("height", "mass"),
digits = 1L, dec.mark = ",", mark = " ") %>%
format_seuil("ratio_j", input$seuil_j)
}
format_seuil <- function(table, column, seuil) {
# Threshold for the aboslute value, and different coloring if higher or lower
formatStyle(table, column,
fontWeight = styleInterval(
c(-seuil / 100, seuil / 100), c("bold", "normal", "bold")),
color = styleInterval(
c(-seuil / 100, seuil / 100), c("red", "black", "orange")
))
}
shinyApp(ui, server)
我可以导出为 pdf 或打印,但显示被修改。我还可以使用rmarkdown 和knitr 生成一个pdf,但这将是工作量的两倍,而且感觉就像我错过了使用按钮扩展的东西。
我希望这很清楚,并感谢您的帮助!
弗洛里安
【问题讨论】:
-
一年前我有一个类似的question,但没有找到直接的解决方案。
标签: javascript css r datatables shiny