Reputation: 8404
Is it possible to download a DT::datatable
as pdf through a shiny
app ?
#app.r
library(shiny)
library(ggplot2)
library(magrittr)
library(DT)
ui <- shinyUI(
fluidPage(
column(3,
downloadButton(
outputId = "downloader",
label = "Download PDF"
)
),
column(
width = 3,
dataTableOutput("table")
)
)
)
server <- shinyServer(function(input, output, session){
#****************************************
#* Reactive Values
table <- reactive({
mtcars
})
#****************************************
#* Output Components
output$table <-
renderDataTable({
table()
})
#****************************************
#* Download Handlers
output$downloader <-
downloadHandler(
"results_from_shiny.pdf",
content =
function(file)
{
rmarkdown::render(
input = "report_file.Rmd",
output_file = "built_report.pdf",
params = list(table = table()
)
)
readBin(con = "built_report.pdf",
what = "raw",
n = file.info("built_report.pdf")[, "size"]) %>%
writeBin(con = file)
}
)
})
shinyApp(ui, server)
and
#report_file.rmd
---
title: "Parameterized Report for Shiny"
output: pdf_document
params:
table: 'NULL'
---
```{r}
params[["table"]]
```
Upvotes: 0
Views: 900
Reputation: 84529
You can try the pdf
button of the Buttons
datatables extension. In this way you don't need a downloadHandler
. Otherwise, below is a solution using the good old xtable
package. For more sophisticated tables, use kableExtra
.
library(shiny)
library(DT)
library(xtable)
library(withr)
library(shinybusy)
ui <- fluidPage(
add_busy_spinner(spin = "cube-grid", onstart = FALSE),
column(
width = 3,
downloadButton(
outputId = "downloader",
label = "Download PDF"
)
),
column(
width = 3,
DTOutput("table")
)
)
server <- function(input, output, session){
table <- reactive({
mtcars
})
#****************************************
#* Output Components
output[["table"]] <- renderDT({
datatable(table())
})
#****************************************
#* Download Handlers
output[["downloader"]] <- downloadHandler(
filename = "results_from_shiny.pdf",
content = function(file){
texfile <- paste0(tools::file_path_sans_ext(file), ".tex")
latex <- print.xtable(
xtable(table()), print.results = FALSE,
floating = FALSE, scalebox = "0.7"
)
writeLines(
c(
"\\documentclass[12pt]{standalone}",
"\\usepackage{graphics}",
"\\usepackage{caption}",
"\\begin{document}",
"\\minipage{\\textwidth}",
latex,
"\\captionof{table}{My caption}",
"\\endminipage",
"\\end{document}"
),
texfile
)
with_dir(
dirname(texfile),
tools::texi2pdf(texfile, clean = TRUE)
)
}
)
}
shinyApp(ui, server)
Upvotes: 2