在 Shiny 中将 save_kable 导出为 pdf

Exporting save_kable as pdf in Shiny

我正在尝试使用 R Shiny 将 kable table (latex) 导出到 .pdf 文件。

这是我用来生成 kable 乳胶的代码 table:

x<-kable(overall, align = c('l', 'c', 'c', 'c', 'c', 'c', 'c'), "latex", booktabs = T,
             caption = "Sample Table",  
             escape = FALSE)%>%
      kable_styling(latex_options = c("striped")) %>%
      add_header_above(c(" " = 1, 'Group 1' = 3, 'Group 2' = 3))%>%
      landscape()

save_kable(x, 'SampleTable.pdf')

我可以在独立的 R 程序中导出它,但我想用 R Shiny 复制导出。我试图将代码包装在 downloadHandler 函数中,但它不起作用。

示例代码:

output$export = downloadHandler(
    filename = function() {"sampleTable.pdf"},
    content = function(file) {
     x<-kable(overall, align = c('l', 'c', 'c', 'c', 'c', 'c', 'c'), "latex", booktabs = T,
         caption = "Sample Table",  
         escape = FALSE)%>%
  kable_styling(latex_options = c("striped")) %>%
  add_header_above(c(" " = 1, 'Group 1' = 3, 'Group 2' = 3))%>%
  landscape()

  save_kable(x, file)
    }
  )

如有任何见解,我们将不胜感激。

这对我有用(安装 pandoctexlive-xetex 之后):


library(shiny)
library(knitr)
library(kableExtra)

library(datasets)
options(knitr.table.format = "latex") # not required in newer versions of kableExtra

server <- function(input, output) {

    # Fill in the spot we created for a plot
    output$phonePlot <- renderPlot({

        # Render a barplot
        barplot(WorldPhones[,input$region]*1000, 
                main=input$region,
                ylab="Number of Telephones",
                xlab="Year")
    })
    output$export = downloadHandler(
        filename = function() {"sampleTable.pdf"},
        content = function(file) {
            x <- kable(WorldPhones, align = c('l', 'c', 'c', 'c', 'c', 'c', 'c'), "latex", booktabs = T,
                     caption = "Sample Table",  
                     escape = FALSE) %>%
                kable_styling(latex_options = c("striped")) %>%
                add_header_above(c(" " = 1, 'Group 1' = 3, 'Group 2' = 3)) %>%
                landscape()

            save_kable(x, file)
        },
        contentType = 'application/pdf'
    )

}

ui <- fluidPage(    

    # Give the page a title
    titlePanel("Telephones by region"),

    # Generate a row with a sidebar
    sidebarLayout(      

        # Define the sidebar with one input
        sidebarPanel(
            selectInput("region", "Region:", 
                        choices=colnames(WorldPhones)),
            hr(),
            helpText("Data from AT&T (1961) The World's Telephones."), 
            shiny::downloadButton("export", "Export")
        ),

        # Create a spot for the barplot
        mainPanel(
            plotOutput("phonePlot")  
        )

    )
)

shinyApp(ui = ui, server = server)