将Shiny(非ggplot)绘图输出为PDF

geo*_*ory 13 r knitr shiny

有没有一种方法可以输出(UI结束)Shiny图到PDF供应用程序用户下载?我尝试过各种类似于涉及ggplot的方法,但似乎downloadHandler无法以这种方式运行.例如,以下内容只会生成无法打开的PDF文件.

library(shiny)
runApp(list(
  ui = fluidPage(downloadButton('foo')),
  server = function(input, output) {
    plotInput = reactive({
      plot(1:10)
    })
    output$foo = downloadHandler(
      filename = 'test.pdf',
      content = function(file) {
        plotInput()
        dev.copy2pdf(file = file, width=12, height=8, out.type="pdf")
      })
  }
))
Run Code Online (Sandbox Code Playgroud)

非常感谢您的帮助.

geo*_*ory 6

解决了.绘图应该在本地保存pdf(),而不是屏幕设备(如同dev.copy2pdf).这是一个有效的例子:shiny::runGist('d8d4a14542c0b9d32786').对于一个不错的基本模型尝试:

server.R

library(shiny)
shinyServer(
    function(input, output) {

        plotInput <- reactive({
            if(input$returnpdf){
                pdf("plot.pdf", width=as.numeric(input$w), height=as.numeric(input$h))
                plot(rnorm(sample(100:1000,1)))
                dev.off()
            }
            plot(rnorm(sample(100:1000,1)))
        })

        output$myplot <- renderPlot({ plotInput() })
        output$pdflink <- downloadHandler(
            filename <- "myplot.pdf",
            content <- function(file) {
                file.copy("plot.pdf", file)
            }
        )
    }
)
Run Code Online (Sandbox Code Playgroud)

ui.R

require(shiny)
pageWithSidebar(
    headerPanel("Output to PDF"),
    sidebarPanel(
        checkboxInput('returnpdf', 'output pdf?', FALSE),
        conditionalPanel(
            condition = "input.returnpdf == true",
            strong("PDF size (inches):"),
            sliderInput(inputId="w", label = "width:", min=3, max=20, value=8, width=100, ticks=F),
            sliderInput(inputId="h", label = "height:", min=3, max=20, value=6, width=100, ticks=F),
            br(),
            downloadLink('pdflink')
        )
    ),
    mainPanel({ mainPanel(plotOutput("myplot")) })
)
Run Code Online (Sandbox Code Playgroud)