Print Leaflet Maps Easily with Leaflet.browser.print Plugin

Are you looking for a straightforward way to Print Leaflet maps directly from your web browser? The Leaflet.browser.print plugin offers a simple and effective solution for incorporating map printing functionality into your Leaflet.js web applications. This guide will walk you through everything you need to know to utilize this powerful plugin, ensuring your users can easily create physical copies of your interactive maps.

What is Leaflet.browser.print?

Leaflet.browser.print is a valuable plugin designed for Leaflet, the leading open-source JavaScript library for mobile-friendly interactive maps. It empowers users to print full-page maps directly from their browsers, enhancing the usability of web maps for offline use, presentations, and record-keeping. Whether you need to print a map in portrait or landscape, define a custom print area, or even add headers and footers, this plugin provides the flexibility you need.

Check out the live demo of the Leaflet print plugin in action to see it working firsthand.

Key Features of the Leaflet Print Plugin

  • Browser-Based Printing: Enables direct printing from the browser without server-side rendering, simplifying the printing process.
  • Multiple Print Modes: Offers various print modes including Portrait, Landscape, Auto (fits all map layers), and Custom (user-defined area) to cater to different printing needs.
  • Flexible Configuration: Provides extensive options for customization, including page size, orientation, print button position, document title, and more.
  • Backend Compatibility: Can be used in both frontend (browser control) and backend environments for more advanced print workflows.
  • Event Handling: Fires a range of events during the print process, allowing developers to hook into different stages for custom actions like adding loading indicators or manipulating map elements.
  • Additional Content Printing: Supports printing of supplementary content alongside the map, such as titles, descriptions, or legends, for richer printed outputs.
  • Extensible Layer Support: Allows registration of new layer types and renderers to ensure compatibility with a wide range of Leaflet layers.

Getting Started with Leaflet.browser.print

Integrating the Leaflet print plugin into your project is quick and easy. Here’s how you can get started:

Installation

You can install Leaflet.browser.print using several package managers or by directly including it as a script in your HTML.

NPM

 npm install --save leaflet.browser.print

YARN

 yarn add leaflet.browser.print

Script Tag

Alternatively, you can include the plugin directly in your HTML file using a <script> tag. Ensure that you have already included Leaflet.js in your project.

 <script src="dist/leaflet.browser.print.min.js"></script>

Basic Usage

Once installed, you can add the print functionality to your Leaflet map in a few lines of code. The plugin offers two main ways to initiate printing: using a Control for browser-based printing or directly through the L.browserPrint class for backend or custom implementations.

Adding a Print Control to Your Map

The most straightforward way to enable leaflet print functionality is by adding a print control to your map. This adds a button directly to your map interface, allowing users to initiate printing with a single click.

 var browserControl = L.control.browserPrint(options).addTo(map);

You can customize the control by passing an options object. Here are some of the key options:

Option Type Default Description
position Leaflet control position 'topleft' Sets the position of the print button on the map (e.g., ‘topleft’, ‘topright’).
title String 'Print map' Sets the tooltip text that appears when hovering over the print button.
printModes Array ["Portrait", "Landscape", "Auto", "Custom"] Defines the available print modes in the control’s dropdown menu.

You can also pass backend options through the control options for consistent configuration across frontend and backend usage.

 L.control.browserPrint({position: 'topleft', title: 'Print ...'}).addTo(map);

For scenarios requiring more control, you can instantiate the L.browserPrint class separately and then pass it to the control. This is useful when you want to reuse the same BrowserPrint instance in both the control and backend logic.

 var browserPrint = L.browserPrint(map, backendOptions);
 L.control.browserPrint(controlOptions, browserPrint).addTo(map);

Here’s a more comprehensive example demonstrating various options, including custom print modes and a custom print action:

 var customActionToPrint = function(context, mode) {
  return function() {
   window.alert("We are printing the MAP. Let's do Custom print here!");
   context._printMode(mode);
  }
 };

 L.control.browserPrint({
  title: 'Just print me!',
  documentTitle: 'Map printed using leaflet.browser.print plugin',
  printLayer: L.tileLayer('https://stamen-tiles-{s}.a.ssl.fastly.net/watercolor/{z}/{x}/{y}.{ext}', {
   attribution: 'Map tiles by <a href="http://stamen.com">Stamen Design</a>, <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a> — Map data © <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>',
   subdomains: 'abcd',
   minZoom: 1,
   maxZoom: 16,
   ext: 'png'
  }),
  closePopupsOnPrint: false,
  printModes: [
   L.BrowserPrint.Mode.Landscape("Tabloid",{title: "Tabloid VIEW"}),
   L.browserPrint.mode("Alert",{title:"User specified print action",pageSize: "A6", action: customActionToPrint, invalidateBounds: false}),
   L.BrowserPrint.Mode.Landscape(),
   "Portrait",
   L.BrowserPrint.Mode.Auto("B4",{title: "Auto"}),
   L.BrowserPrint.Mode.Custom("B5",{title:"Select area"})
  ],
  manualMode: false
 }).addTo(map);

To programmatically stop the printing process, you can call the cancel() method on the control instance:

 browserControl.cancel();

Using Leaflet.browser.print in the Backend

For backend usage or more programmatic control over printing, you can instantiate L.browserPrint directly without the control.

 var browserPrint = L.browserPrint(map, options);

Then, you can initiate printing using the print() method, specifying the desired print mode:

 browserPrint.print(L.BrowserPrint.Mode.Landscape());

To cancel printing in backend mode, use the cancel() method:

 browserPrint.cancel();

The options object passed to L.browserPrint in backend mode can include the following:

| Option | Type | Default | Description

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *