Outputting Shiny (non-ggplot) plot to PDF

knitr, r, shiny

Solution

Solved. The plot should be saved locally with `pdf()`, not the screen device (as with `dev.copy2pdf`). Here's a working example: `shiny::runGist('d8d4a14542c0b9d32786')`. For a nice basic model try:

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)
            }
        )
    }
)

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")) })
)

Problem

Is there a method to output (UI end) Shiny plots to PDF for the app user to download? I've tried various methods similar to those involving ggplot, but it seems `downloadHandler` can't operate in this way. For example the following just produces broken PDF's that don't open. ``` 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") }) } )) ``` Very grateful for assistance.

Original source