Shiny leaflet easyPrint plugin

谁说胖子不能爱 提交于 2019-11-29 07:19:08

Solution

  library(leaflet)
  library(shiny)
  library(htmlwidgets)

  jsfile <- "https://rawgit.com/rowanwins/leaflet-easyPrint/gh-pages/dist/bundle.js" 
  ui <- fluidPage(
    tags$head(tags$script(src = jsfile)),
    leafletOutput("map")
  )

  server <- function(input, output, session) {

    output$map <- renderLeaflet({
      leaflet() %>% 
        addProviderTiles("OpenStreetMap.Mapnik") %>%
        setView(-122.23, 37.75, zoom = 10) %>%
        onRender(
          "function(el, x) {
            L.easyPrint({
              sizeModes: ['Current', 'A4Landscape', 'A4Portrait'],
              filename: 'mymap',
              exportOnly: true,
              hideControlContainer: true
            }).addTo(this);
            }"
        )
      })

    }

  shinyApp(ui, server)

Note: leaflet-easyPrint depends on dom-to-image. Per the dom-to-image Readme, Safari and Internet Explorer are not supported. However, the print button will work in Chrome and Firefox.

Troubleshooting Process

If we run the app and inspect element, we see the following errors:

Let's start with the second and third errors.

Failed to load resource

This error is pretty self-explanatory: the URL https://github.com/rowanwins/leaflet-easyPrint/blob/gh-pages/dist//index.js doesn’t exist. The path is wrong: index.js doesn’t exist in the dist directory.

We want to use bundle.js with this path: https://github.com/rowanwins/leaflet-easyPrint/blob/gh-pages/dist/bundle.js.

Did not load script

GitHub uses strict MIME type checking, so the browser isn’t using the file as intended. We need to use a rawgit.com path instead. Read more here. To write a rawgit.com path, follow these steps (from the linked answer):

  1. Find your link on GitHub, and click to the "Raw" version of the file.
  2. Copy the URL, and link to it.
  3. Change raw.githubusercontent.com to rawgit.com (non-production) or cdn.rawgit.com (production)

We should use this path: https://rawgit.com/rowanwins/leaflet-easyPrint/gh-pages/dist/bundle.js

TypeError: L.easyPrint is not a function

The error occurred before the errors from loading leaflet-easyPrint. This tells us that onRender is getting called before leaflet-easyPrint is loaded and attached to the widget. Per Joe Cheng in this thread, htmldependency injection at runtime can be asynchronous. He recommends against using htmlDependency(src = c(href = "http://...")) for any dependency that's intended to be used with Shiny.

Instead, we can just include the remote JS file in the header of the app. Then leaflet-easyPrint will be loaded before onRender is called.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!