我已经在Shiny应用程序中创建了一个leaflet地图。现在我需要一个下载按钮,这样用户就可以将当前显示的地图(包括所有标记、多边形等)作为pdf文件下载。
我发现了如何在R中保存leaflet地图的解决方案:How to save Leaflet in R map as png or jpg file?
但是在Shiny中该怎么做呢?我保持示例代码简单,但请考虑一下,在用户希望将地图保存为pdf之前,通过leafletProxy()进行了大量更改。
这是我的尝试,但它没有起作用。
server.R
library(shiny)
library(leaflet)
library(devtools)
install_github("wch/webshot") # first install phantomjs.exe in your directory
library(htmlwidgets)
library(webshot)
server <- function(input, output){
output$map <- renderLeaflet({
leaflet() %>% addTiles()
})
observe({
if(input$returnpdf == TRUE){
m <- leafletProxy("map")
saveWidget(m, "temp.html", selfcontained = FALSE)
webshot("temp.html", file = "plot.pdf", cliprect = "viewport")
}
})
output$pdflink <- downloadHandler(
filename <- "map.pdf",
content <- function(file) {
file.copy("plot.pdf", file)
}
)
}
ui.R
ui <- fluidPage(
sidebarPanel(
checkboxInput('returnpdf', 'output pdf?', FALSE),
conditionalPanel(
condition = "input.returnpdf == true",
downloadLink('pdflink')
)
),
mainPanel(leafletOutput("map"))
)