![](/img/trans.png)
[英]How to generate simple html table using Shiny and R without using renderTable function?
[英]How we can download rendertable in pdf format in R shiny without losing HTML tags that I used in the table
output$TextTable <- renderTable({
varsub
}, width = "92%", include.colnames = TRUE, spacing = "xs",
sanitize.text.function = identity)
##我想使用下载按钮或链接下载此可渲染文件。
将此添加到服务器部分:
output$downloadData <- downloadHandler(
filename = function() {
paste("test.csv")
},
content = function(file) {
write.csv(varsub(), file, row.names = FALSE)
}
)
接下来,将其添加到您的 ui 旁边,如下所示:
tableOutput("TextTable"),
downloadButton("downloadData", "Download")
您也可以参考此文档https://shiny.rstudio.com/reference/shiny/0.14/downloadHandler.html
这是使用 JavaScript 库jspdf和dom-to-image 的方法。 您必须在按钮的data-tableid
属性中设置表 ID。
library(shiny)
js <- "
function tableExport(tableId){
var $table = $(document.getElementById(tableId));
var captionHeight = 8 + ($table.find('caption').height() || 0);
var container = $table.parent();
var $el = container.hasClass('tableContainer') ? container : $table;
var width = $el.width();
var height = $el.height() + captionHeight;
domtoimage.toPng($el[0], {width: width, height: height})
.then(function (blob) {
var pdf = new jsPDF('l', 'pt', [width, height]);
pdf.addImage(blob, 'PNG', 0, 0, width, height);
pdf.save('table.pdf');
});
}
"
CSS <- "
.tableContainer>* {
margin-top: 0;
}
"
ui <- fluidPage(
tags$head(
tags$script(src = "https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"),
tags$script(src = "https://cdnjs.cloudflare.com/ajax/libs/dom-to-image/2.6.0/dom-to-image.min.js"),
tags$script(HTML(js)),
tags$style(HTML(CSS))
),
br(),
tableOutput("theTable"),
actionButton(
"export", "Export table to PDF",
"data-tableid" = "theTable",
onclick = "tableExport($(this).data('tableid'));"
)
)
server <- function(input, output, session){
output[["theTable"]] <- renderTable({
data.frame(
col1 = c("<span style='color:red;'>AAA</span>", "BBB"),
col2 = c("CCC", "DDD")
)
}, width = "92%", include.colnames = TRUE, spacing = "xs",
sanitize.text.function = identity,
caption = "My table", caption.placement = "bottom")
}
shinyApp(ui, server)
如果要为表格添加标题,请执行以下操作:
div(class = "tableContainer",
tags$h3("Table title"),
tableOutput("theTable")
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.