Giter VIP home page Giter VIP logo

leaflet.browser.print's Introduction

Map Print Plugin for Leaflet.js

npm version

General information

A leaflet plugin which allows users to print full page map directly from the browser

  • Pros:

    • Compatible with Leaflet v1+.
    • Any page size from range A0-A10, B0-B10, C0-C10, D0-D10 can se used.
    • North American paper sizes available as well: Letter, HalfLetter, Legal, JuniorLegal, Tabloid, Ledger
    • Available 4 print modes, you can chose any you want and even create your own.
    • Everything in browser, no external apps or dependencies, print your map in one click.
    • You can even override default browser print behavior and export map as image, more details you can find here.
    • Any additional page content can be printed together with a map.
    • Leaflet Print Control
    • And many more...just ask!
  • Cons:

Changelog

Other examples:

Check out the:

Be careful when printing map legend

Common problem with printing map with a legend is external CSS plugins that ruins everything, here is an actual good answer why it is like that with Bootstrap plugin. Please read it carefully.

Downloads

NPM

	npm install --save leaflet.browser.print

YARN

	yarn add leaflet.browser.print

SCRIPT

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

Usage

Add a Control

Add the following line of code to your map script

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

You can pass a number of options to the control:

Option Type Default Description
position Leaflet control position 'topleft' Position the print button
title String 'Print map' Sets the text which appears as the tooltip of the print button
printModes Array ["Portrait", "Landscape", "Auto", "Custom"] Collection of page print actions

Also the options for the [backend](#Use it in the Backend) can passed through.

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

To use the same BrowserPrint class in the backend and in the control you can pass it while creating the control:

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

Here's an example of passing through some options:

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> &mdash; Map data &copy; <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 stop printing call cancel():

browserControl.cancel();

Use it in the Backend

Add the following line of code to your map script

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

And then you can start printing with:

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

To stop printing call cancel():

browserPrint.cancel();

You can pass a number of options for printing:

Option Type Default Description
printModes Array ["Portrait", "Landscape", "Auto", "Custom"] Collection of page print actions
documentTitle String '' Sets the text which appears as the print page title
printLayer Leaflet tile layer null A tiles layer to show instead of all current active tile layers
closePopupsOnPrint Boolean true Indicates if we need to force popup closing for printed map
contentSelector String "[leaflet-browser-print-content]" Content selector for printed map, will select and dynamically inject content on printed maps. For full functionality please check "Printing additional content section"
pagesSelector String "[leaflet-browser-print-pages]" Pages selector for printed map, will select and dynamically inject additional pages content on printed maps.
manualMode Boolean false Adds a button with id='leaflet-browser-print--manualMode-button' for debugging purpose, also can be used to print map with external button.
customPrintStyle Polyline options { color: "gray", dashArray: "5, 10", pane: "customPrintPane" } Style for rectangle on custom print. 'customPrintPane' - is a custom pane with z-index => 9999
cancelWithEsc Boolean true Cancel printing with the ESC key
printFunction Function window.print Function that will be executed for printing.
debug Boolean false Stops opening the print window. Only for developing use.

Here's an example of passing through some options:

var options = {
    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> &mdash; Map data &copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>',
                    subdomains: 'abcd',
                    minZoom: 1,
                    maxZoom: 16,
                    ext: 'png'
                }),
    closePopupsOnPrint: false,
    manualMode: false
};
var browserPrint = L.browserPrint(map, options);

Print Modes

Mode Description
Portrait Print currently visual part of the map with Portrait page dimensions
Landscape Print currently visual part of the map with Landscape page dimensions
Auto Track all active map layers (markers, lines, polygons, etc. ) and tries to fit them in print page in Portrait or Landscape page dimensions
Custom Allows you to select rectangle for printing, and then fit it in Portrait or Landscape page dimensions if it is not explicit set

General modes:

	L.BrowserPrint.Mode.Landscape();
	L.BrowserPrint.Mode.Portrait();
	L.BrowserPrint.Mode.Auto();
	L.BrowserPrint.Mode.Custom();

For each general mode the page size and options can be passed. The default page size is A4

L.BrowserPrint.Mode.Landscape(pageSize,options);
Option Type Default Description
title String The mode name. f.e. "Portrait" Set the control menu text
pageSize String 'A4' Size of page that will be printed
orientation String Mode name or calculation (Auto & Custom) How the page will be displayed landscape or portrait
zoom Integer 0 Zoom the map to this level
enableZoom Boolean true Zoom the map optimal, else the current zoom is taken. zoom have to be 0
action Function default mode action [Custom print button action](#Custom print button action)
rotate Integer 0 Rotate the map x-times by 90°
margin Object automatic The default margin are (height + width) / 39.9. A number can passed for all margins or set it explicit in a object for left, right, top, bottom --> {left: 10, top: 40}
scale Double 1 Scale the map. Shows all bigger or smaller, with 1 the map looks normal
header Object Adds a header section to the top of the page. For the available options look in the "Header / Footer Options" table below
footer Object Adds a footer section to the bottom of the page. For the available options look in the "Header / Footer Options" table below

Header / Footer Options

Option Type Default Description
enabled Boolean false Shows the section
text String / HTML "" The displayed text
size String "10mm" The height of the section
overTheMap Boolean false The section is displayed over the map

You can overwrite the CSS or change the DOM over the ids #print-header and #print-footer

Creating a own mode: L.BrowserPrint.Mode(name,options);

L.browserPrint.mode("Alert Mode",{pageSize: 'A3',orientation: 'Portrait'});

The mode options can be updated with:

mode.setOptions(options);

Map Events

Map Event Event Shortcut Value Description Purpose
browser-print-init L.BrowserPrint.Event.PrintInit { mode } Fire right after printing was initialized. To support busy indicator of any type to show user loaing status.
browser-pre-print L.BrowserPrint.Event.PrePrint { pageSize, pageBounds, printObjects } Fire before print started, allows manipulation with map objects. For DOM manipulation with real map objects.
browser-print-start L.BrowserPrint.Event.PrintStart { printLayer, printMap, printObjects } Fire on print started, before all print calculations is done. For DOM manipulation with print map and print objects.
browser-print L.BrowserPrint.Event.Print { printLayer, printMap, printObjects } Fire right before native print. For DOM manipulation with print map and print objects.
browser-print-end L.BrowserPrint.Event.PrintEnd { printLayer, printMap, printObjects } Fire on print end, after we refresh map to show initial view. For DOM manipulation with real map objects after print
browser-print-cancel L.BrowserPrint.Event.PrintCancel { mode } Fire when printing cancelded For DOM manipulation with real map objects after cancel

Example can be found here: DEMO with print objects manipulations;

Printing additional content section

To add additional printing content (in addition to a map itself) we need to specify content that should be added: Demo; By default contentSelector: '[leaflet-browser-print-content]' so we need a content with an 'leaflet-browser-print-content' attribute.

Code example:

<style leaflet-browser-print-content>
	.grid-print-container { // grid holder that holds all content (map and any other content)
		grid-template: auto 1fr auto / 1fr;
		background-color: orange;
	}
	.grid-map-print { // map container itself
		grid-row: 2;
	}
	.title { // Dynamic title styling
		grid-row: 1;
		justify-self: center;
		color: white;
	}
	.sub-content { // Dynamic sub content styling
		grid-row: 5;
		padding-left: 10px;
	}
</style>
<h1 class="title" leaflet-browser-print-content>Leaflet Browser print TITLE</h1>
<h3 class="sub-content" leaflet-browser-print-content>Leaflet Browser print SUB TITLE text</h3>

On print, plugin will scan DOM by contentSelector, and will add content to print may.

We are using CSS-GRID to position all controls on a print page.
Therefor it's not supportable in all browsers, for more information please visit [caniuse.com](https://caniuse.com/#feat=css-grid).

Angular 2+

See chapter 4 of https://github.com/Asymmetrik/ngx-leaflet-tutorial-plugins/tree/master/Leaflet.BrowserPrint

New print layers/renderers registration

To add missing print layers you need to explicitly indicate layer, it's identifier and construction function that will return actual layer object.

Example of L.MarkerClusterGroup registration:

L.BrowserPrint.Utils.registerLayer(
	// Actual typeof object to compare with
	L.MarkerClusterGroup,
	// Any string you would like for current function for print events
	'L.MarkerClusterGroup',
	function (layer, utils) {
		// We need to recreate cluster object with available options
		// Here we use function, but we can use object aswell,
		// example: new L.MarkerClusterGroup(layer._group.options);
		var cluster = L.markerClusterGroup(layer._group.options);

		// And we clone all inner layers to our new cluster
		// to properly recalculate/recreate position for print map
		cluster.addLayers(utils.cloneInnerLayers(layer._group));

		return cluster;
	});

List of pre-registered layers available for printing:

  • L.TileLayer.WMS
  • L.TileLayer
  • L.ImageOverlay
  • L.Marker
  • L.Popup
  • L.Circle
  • L.CircleMarker
  • L.Rectangle
  • L.Polygon
  • L.MultiPolyline
  • L.MultiPolygon
  • L.Polyline
  • L.GeoJSON
  • L.FeatureGroup
  • L.LayerGroup
  • L.Tooltip

Example of renderer registration:

L.BrowserPrint.Utils.registerRenderer(L.SVG, 'L.SVG');

List of registered renderers

  • L.SVG
  • L.Canvas

If you want to override any of those, please register your own builder for them.

MarkerClusterGroup OutOfMemory problem:

If you are facing OutOfMemory problem printing huge amount of objects you may consider next workaround:

// markerClusterGroup to print
var printableObjects = L.markerClusterGroup();

// We are not cloning markercluster to preserve original clasterization behavior and prevent OutOfMemory problems
// This way we will need to invalidate MarkerClusterGroup after printing
L.BrowserPrint.Utils.registerLayer(L.MarkerClusterGroup,
										  'L.MarkerClusterGroup',
											function (layer, utils) {
												return layer;
											});

// On print end we invalidate markercluster to update markers;
map.on(L.BrowserPrint.Event.PrintEnd, function(e) {
	map.removeLayer(printableObjects);
	map.addLayer(printableObjects);
});

// Initial rendering ouf objects
map.addLayer(printableObjects);

Download Map as Image

To download map as PNG you have to use external plugin to do the job. Current plugin will do only 1 job - prepare map for printing. To print actual map we use in-browser print mechanism:

window.print()

You can use the options printFunction to implement any other behavior that you want. Example with domtoimage plugin to export map as image.png:

var saveAsImage = function () {
	return domtoimage.toPng(document.body)
        .then(function (dataUrl) {
            var link = document.createElement('a');
            link.download = map.printControl.options.documentTitle || "exportedMap" + '.png';
            link.href = dataUrl;
            link.click();
        });
};

L.control.browserPrint({
    documentTitle: "printImage",
    printModes: [
        L.BrowserPrint.Mode.Auto("Download PNG"),
    ],
    printFunction: saveAsImage
}).addTo(map);

Full example you can find here.

Custom print button action

Example of how you can use default button or style/specify your own button to call actual print logic. First of all you need to create print plugin with at least one print option to be able to attach it to the map, later you can use any other, even dynamically created print mode with your custom print button.

Example:

    L.control.browserPrint({
        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> &mdash; Map data &copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>',
                    	subdomains: 'abcd',
                    	minZoom: 1,
                    	maxZoom: 16,
                    	ext: 'png'
                    }),
		printModes: [ "Landscape" ],
		manualMode: true // use true if it's debug and/or default button is okay for you, otherwise false.
    }).addTo(map);

	document.querySelector("#custom_print_button").addEventListener("click", function(){
		var modeToUse = L.BrowserPrint.Mode.Auto();
		map.printControl.print(modeToUse);
	});

And add next css to hide onmap menu:

	.leaflet-control-browser-print {display: none;}

Important notes

Unfortunately 'Custom' mode is not working correctly for Leaflet v.0.7.7 in all IE browsers.

Acknowledgements

Thanks to Rowan Winsemius for general idea with a map print functionality.

Thanks to Jan Pieter Waagmeester for an idea that helped with map print functionality.

Also thanks to IcoMoon for the print icon.

Thanks to Falke-Design for restructuring the project and adding more functions

leaflet.browser.print's People

Contributors

appleshowc avatar beedyg avatar falke-design avatar igor-vladyka avatar jude avatar julien-noblet avatar sgrillon14 avatar skirridsystems avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

leaflet.browser.print's Issues

Can't print layers included in custom panes

Hi,
first thank you for your great work on this plugin.
I m using leaflet and angular5.
I add geojson layers to a map with custom pane option like this:

this.layerOne = L.geoJSON(this.levelOne, { pane: "firstPane", style: style, onEachFeature:onEachFeature}); this.layerOne.addTo(this.mapService.map)

But i get an error:

TypeError: Cannot read property 'appendChild' of undefined

If i remove the "pane" option in each layer i get no error. Is the pane option supported on this plugin?

Export Map to PNG

Is there any way to export to png instead of printing? Would be a nice feature to add to a Print / Export menu.

Adding title to map

Hi,
first of all thanks for the great tool. Works great!
I have one question though: Is there the opportunity to add a title or subtitle to the map?
(I don't know if this is right place to ask of if there is something like a mailing list.)

Regards,
Peter

Print orientation on IE / Edge / Firefox

Hello,

It is not possible to change page orientation on IE 11, Edge and Fifrefox.
For firefox :

  • The last page print orientation is saved and it is not automatically changed/forced by the plugin option.

For IE11 / Edge

  • Orientation is always set to "Portrait"
  • When I change orientation to landscape, some layers / controls are lost or broken (I lose color on countries).

This can be reproduced on the leaflet.browser.print demo :
https://igor-vladyka.github.io/leaflet.browser.print/

Best regards,

Problems in printing tooltips and markercluster

Hello,

Thanks for the library. It helps a lot to print the map for leaflet!
It is found that the tooltips and markerclusters are unable to be printed with styles. Is there documentation or demo for solving these issues? Thanks a lot.

It works now. I updated css and fixed the issues. Thank you.

Print button outside the map

I want to have the print button outside the map, so i appended that button on a div outside the map, but nothing happend when i click on the options.
Any advice?

A0 size print doesn't fit into print screen.

I am trying to print leaflet map with A0 size but map does'nt completely fit on print screen. Print screen discards half of map width. Same issue occurs in A1, A2, A3. Print after size A4 works perfect.

I have attached screen shots of issue and jsfiddle of my code.

One more thing I need to know. Is there any way to increase font size of header and discard URL in footer?

map in browser

map in print screen

Code Sample

http://jsfiddle.net/sirajjunior/LnzN2/6288/

css Eliminated when printing controls

hello lgor!
when i print my map with a scale control ,it works well in (please copy it to browser url for visit)
hancc.xyz
but when i deploy the plugin in my own project built with vue ,troubles came and i could find the key to solve it, could u give me a hand ? thanks!
the code below i used both in the two demo, set the BrowserPrint options [manualMode:true] and see what happens in printed page.
L.control.browserPrint({//etc... manualMode: true}); L.control.scale({position:'topleft'}).addTo(map);
the printing progress :
css(the white background) works in manualMode:true printing page:
in printing page
when i push the 'print' button i shoud get the pdf like :
2776446059
in face it is like:
2537971359
the css is removed , and the words (100KM and 50mi) in the scale control can be selected like other words in html. actually, all the css will be eliminated when i push [print] button..
thanks a lot!
han

Zoom change on print

Hi, can I disable the zoom change on print? I want it to print the exact same zoom level as is.

Leaflet.markercluster: issue printing white clusters in Firefox

When I use Leaflet.markercluster: any clusters display fine on the print preview page BUT when you actually get the print off the printer the clusters have lost their colour settings and the circles are just white.

To see this go to https://www.derbyramblers.org.uk/walk-details/map-of-walk-locations.html
Print the page either to paper or PDF
I would have expected the same attributes of the clusters to get printed, color, font etc
This happens if I am using Firefox 64. but works fine in Chrome.

PS thanks for great extension.

Create image

Hello, I am using your plugin and I would like to know if there would be the possibility of instead of loading the map alone and calling the browser function to print that would create an image directly. Thank you

I'm using leaflet 1.3.1 and the search engines for firefox and chrome

How to add legend to map?

Hello,
I love your plugin, it is super simple and easy to set up, however I am having trouble figuring out how to include my maps legend in the print? Is there an option that I am missing?
Thanks for your help.

Icon disappear when located plugin in the 'topright' or 'bottomright'.

Hi Igor,

Thanks for your simple yet useful plugin.
I can use your plugin with very easy steps. But when I located the plugin in 'topright' or 'bottomright', the printer icon is disappear when I hover the mouse over it.

Need your guidance please.
Thanks.

note: L.browserPrint({position: 'topright'}).addTo(map);

A3 printing

How can i adjust to add A3 landscape print as an option, i thought i'd seen this on one of the demos but clicking again it's not there. When i use landscape or portrait it defaults to an A4 page size

marker.ClusterGroup not working

Dear Igor,
I would like your help with the following:
I have a markerClusterGroup with almost 500 markers, when I zoom in and marker.ClusterGroup shows many markes, browser.print works ok, but when zoomed out and marker.ClusterGroup shows only a few or no markers, browser.print throws me an error: too much recursion.

What am I doing wring?
Please advice

image

can't print Google and Bing basemaps

I use the mutant-google and the leaflet-bing plugins to display google and bing basemaps. When I use browser-print, the Google basemap is not displayed and I have a "No value provided for variable {subdomain}" error for Bing. Other basemaps (cartoDB, OSM...) are printed fine.
When using the standard chrome print menu, all basemaps are correctly printed.

A sample code reproducing the case is provided (I've just hidden my API key values).
bug print plugin.html.txt

Print with scale

Hi, good work !

my questions :

  1. Is it possible to print map in scale ?
  2. Is it possible start print scale with external button ? (no inside map like your sample)

Icons not loaded while printing.

Hi,
I have this small issue which i dont undertand. when i print the map the leafeltIcons are not show. I use another plugin leaflet.awesome-markers which has a base icon and another glyphicon or fontawesome icon on top.
the glyphicon and fontawesome icons are shown however the base icon which comes from the plugin are not.
here are images for a better understanding
printimage
printimage2

Any help is appreciated.
Thanks in advance.

Popup options ignored

Hi,
when setting closePopupsOnPrint to false, the plugin prints the popup ignoring its options.
For example in my code I set popup option to 'maxWidth:400' to display all my content inside the popup box but when printing with your plugin, the content stick out the popup box.
Standard print through browser menu is ok.
Thx

printing layers with cql_filter

Hi,
I use this plugin to print WMS layers with CQL filters but the cql_filter does not apply when printing...
for example the following wms layer has a cql_filter that filters the states with population over 2M:
L.tileLayer.wms('https://ahocevar.com/geoserver/wms', { layers: 'topp:states', CQL_FILTER: 'PERSONS > 2000000', styles: '', format: 'image/png', transparent: true, }).addTo(map);
result:
pppp

Can you delivery minified and uncompressed in your dist folder?

Can you delivery minified and uncompressed in your dist folder?

your webpack.config.js:

entry: ['./src/leaflet.browser.print.js', './src/leaflet.browser.print.utils.js'],
output: { filename: 'leaflet.browser.print.min.js', path: path.resolve(__dirname, 'dist') },

evolution track:

entry: {
    "leaflet.browser.print": ['./src/leaflet.browser.print.js', './src/leaflet.browser.print.utils.js'],
    "leaflet.browser.print.min": ['./src/leaflet.browser.print.js', './src/leaflet.browser.print.utils.js'],
},
output: { filename: '[name].js', path: path.resolve(__dirname, 'dist') },

More information on https://stackoverflow.com/questions/25956937/how-to-build-minified-and-uncompressed-bundle-with-webpack

tooltip issue

hi, there!
thanks for this lib, it helps a lot
After binding tooltips to polygons print can't proceed to the end, and there are no tooltips on polygons.

printing all of the active tile layers

I have a map with one background layer and some wms layers. it prints only one of the tile layers(the last one that added to the map)... is there any way to get all of the tile layers when printing?
thanks

Print map size follow screen size

I need to print the map not as defined A or B sizes. Rather, the print should follow the size of the displayed map in the client's screen. Is it possible to do so?

Not giving id to button

Is your feature request related to a problem? Please describe.
Hello. I use your plugin in a page witch contain several leaflet maps.
So I have multiple id leaflet-browser-print in my page !

Describe the solution you'd like
Could you avoid using id and use class instead ?

desync basemap

Hi
when using the plugin my basemaps are desync: tiles around print area aren't refreshed and zoom is impossible (no console error). A workaround is to manually select another basemap after printing but I don't know how to code that in my page.
I've attached my map and code.
Greetings
bug_print_fdc_google.zip

Problem trying to print Map

I'm trying to print a map div using only L.browserPrint({ position: 'topright' }).addTo(map); and it works fine when map is empty.

As soon as I put my polygons and layers it doesn't work anymore. I'm gettint this error:
image
I've tried to disable messagebox, canvas and an L.control I use to display a legend, but no success :(

That's the code I use to plot my polygons on map:

var camadas = L.featureGroup().addTo(map);
 var popup = L.popup();
 function plotarPoligonos() {
     map.closePopup();
     camadas.clearLayers();
     // var WEIGHT = 1, FILL_OPACITY = .50;
     for (var i = 0; i < $scope.retornoPesquisa.length; i++) {
         var polParse = JSON.parse($scope.retornoPesquisa[i].Poligono);

         if ($scope.retornoPesquisa[i].HtmlRetorno && $scope.retornoPesquisa[i].HtmlRetorno.length > 0) {
             polParse.properties.HtmlRetorno = $scope.retornoPesquisa[i].HtmlRetorno;
             var _templateScope = $scope.$new();
             var compiled = $compile(polParse.properties.HtmlRetorno)(_templateScope);
             polParse.properties.Popup = compiled[0];
         }
         polParse.properties.CorPoligono = $scope.retornoPesquisa[i].CorPoligono;

         var pol = L.geoJSON(polParse, {
             onEachFeature: function (feature, layer) {
                 if (polParse.properties.HtmlRetorno && polParse.properties.HtmlRetorno.length > 0) {
                     layer.on('click', function (e) {
                         popup.setLatLng(e.latlng).setContent(feature.properties.Popup);
                         popup.openOn(map);
                     });
                 }
             },
             style: function (feature) {
                 return {
                     fillColor: polParse.properties.CorPoligono,
                     color: 'grey',
                     weight: 1,
                     fillOpacity: 0.5
                 };
             }
         }).addTo(camadas);
     }
     map.fitBounds(camadas.getBounds());
 };

Graphic or legend display problem

Hello
I just integrated the pluggin into an application. It works but I would like to know why I can not print a graphic. I test manual mode or the graph is displayed but when printing it is no longer there.
thank you for your understanding
mode_manuelle

mode_auto

v1.2.0 Example not showing print button

https://igor-vladyka.github.io/leaflet.browser.print/examples/v1.2.0.html

I am trying to follow the example codes, but this one is not working.

No print icon is shown on the map.

Error in Chrome Console:

Uncaught TypeError: Cannot read property 'printModesNames' of undefined
    at Function.L.control.browserPrint (leaflet.browser.print.js:598)
    at v1.2.0.html:47

Solution, you can add a title and documentTitle

    ctlPrint = L.control.browserPrint({
        title: 'mapName',
        documentTitle: 'mapName'
    }).addTo(map);

example with angular

Hello,

I'm trying to integrate your plugin in an angular application but I've not succeeded...

My map looks like this in my html code :
``<div leaflet style="height: 450px;"
[leafletLayers]="layers"
[leafletLayersControl]="layersControl"
[leafletFitBounds]="fitBounds">

Do you have un example ?

Thanks in advance for your help.

marker size in print view fail

Hello, I am incorporating the option to print in my report, at the moment of generating the impression view the points change drastically. I'm using R, leaflet 0.7+ for R, easyprint 0.4. The code to include the plugin is:

m <- leaflet ()%>%
   onRender ("function (el, x)
            {L.control.browserPrint (
            {title: 'Print Map',
             documentTitle: 'DIGESA - VECTORS',
             printModes: ['Portrait', 'Landscape', 'Auto', 'Custom'],
             manualMode: false,
             printModesNames: {Portrait: 'Vertical', Landscape: 'Horizontal', Auto: 'Auto', Custom: 'Select'}
            }
            ) .addTo (this);} ")%>%

All printing modes have the same behavior.
Some clue as to how to solve it myself would be of great help, thanks in advance, apologies for using google translator.

image

Print View

image

browser-print-start fires after L.browserPrintUtils.cloneLayer

I have a demo page, https://gvarela1981.github.io/leaflet.browser.print/examples/v1.0.3.html
It has a filled red circle and a green circle.
When I press the print button 'browser-print-start' fires and it should set the red circle's fill to 'false' but it does not.
Then I set a new event 'pre-print' into the <leaflet.browser.print.min.js> before calling to L.browserPrintUtils.cloneLayer.
The second demo page https://gvarela1981.github.io/leaflet.browser.print/examples/v1.0.3-pre-print-example.html shows the red circle's fill get transparent before the printing, and then returning to a red fill as the event browser-print-end is executed.

how to add a new EXTEND register?

hello, dear lgor:
I define a new type VectorGrid by :

L.VectorGrid = L.GridLayer.extend({
// A factory method which will be used to instantiate the per-tile renderers.
rendererFactory: L.svg.tile,
// A data structure holding initial symbolizer definitions for the vector features.

vectorTileLayerStyles: {},
initialize:function(option){L.setOptions(this, options);
        L.GridLayer.prototype.initialize.apply(this, arguments);
        if (this.options.getFeatureId) {
            this._vectorTiles = {};
            this._overriddenStyles = {};
            this.on('tileunload', function(e) {
                var key = this._tileCoordsToKey(e.coords),
                    tile = this._vectorTiles[key];

                if (tile && this._map) {
                    tile.removeFrom(this._map);
                }
                delete this._vectorTiles[key];
            }, this);
        }
        this._dataLayerNames = {};}
)

now i use the VectorGrid type to define a city's boundarys ,how to add the register?
very thanks !
han

Leaflet.markercluster: clusters partially brokens when printing

Hello!
I have map with Leaflet.markercluster layer. When I trying to print it I have only text labels from clusters and all text labels from original makers (without clustering).
Is Leaflet.markercluster compatible with browser.print or here are some bugs exists?
Thank you for help!

Display is just blank

Hello
I have just added your extension to a leaflet map.
I added the js file and added the print control
When I hover over the print icon the four options appear.
Whichever of the four I click on the screen goes completely blank and then the printer dialogue appears.
I am using Leaflet 1.3.1
I get one error message that I do not understand
Unknown property 'size'. Declaration dropped. index.php:1:333
as line one is doctype and line 133 is blank.

I am not sure how to debug this?

IE 11 custom print issues

I didn't notice any warning in the readme about this, so posting here.

Using the demo site here:
https://igor-vladyka.github.io/leaflet.browser.print/

in IE 11, the background map (stamen watercolor) and markers show up, but not the feature polygons, or popup "balloon" layer (only popup text shows). I'm attempting to print directly to a PDF with a "print to PDF" print driver. There is no "print preview", but I assume that is an artifact of IE versus Chrome capabilities. Also, the orange CSS background colors are lost, in the IE 11 print

pic from IE 11 PDF output:
image

This workflow (print to PDF) does work with Chrome browser.
pic from Chrome PDF output:
image

Please let me know if there is another option to make this work in IE 11...

Multiple renderers causing duplicate elements on print overlay

Describe the bug
When utilizing multiple map renderers such as SVG and Canvas, the print overlay shows duplicates for records tied to the non-default map renderer.

To Reproduce
Steps to reproduce the behavior:

  1. Create simple map with default options (uses default SVG renderer)
  2. Create new canvas renderer with L.canvas();
  3. Add object to map using the canvas renderer.
  4. Click the print button using any mode
  5. Duplicate copies of the canvas rendered object are shown in the print overlay and print preview

Expected behavior
There should only be one copy of each layer showing in the print overlay and print preview

Example
https://jsfiddle.net/shannonthurston_nuvolo/9hn73j84/

Additional context
I experimented with the code and found that when the layers are cloned for the print overlay the 'renderer' option isn't getting tied to the cloned renderer(L.SVG or L.Canvas), but instead is being left to the original renderer from the underlying map and that is what seems to be causing the issue of duplication. I can make the problem go away partially by modifying the builder functions to set the renderer option to null, but ideally the cloned layers should link to the cloned renderer.

Loading until load service

Hi,
In my project, the service takes 4 seconds to get data and until I got a 200 response nothing happen. And when I have a response, the window.print is fired.

Have a way to display some loading or something like that?

Thanks.

warning with new leaflet version

Hi,
I have the following warning in console with your plugin since Leaflet v.1.3.1: "L.browserPrint(options) is obsolete and will be removed shortly, please use L.control.browserPrint(options) instead."

Plugin crashes if leaflet routing machine is used.

leaflet.browser.print.min.js:10 Uncaught TypeError: Cannot read property 'addTo' of undefined
at NewClass._setupPrintMap (leaflet.browser.print.min.js:10)
at NewClass._addPrintMapOverlay (leaflet.browser.print.min.js:10)
at NewClass._print (leaflet.browser.print.min.js:10)
at NewClass._printPortrait (leaflet.browser.print.min.js:10)
at HTMLLIElement.handler (DomEvent.js:72)

To reproduce, simply include leaflet routing machine in any of your examples, and add a routing control to the map:

var routingControl = L.Routing.control({
routeWhileDragging: false,
showAlternatives: false,
useZoomParameter: true,
show: false,
collapsible: true,
lineOptions: {
addWaypoints: true
},
position: 'bottomright'
}).addTo(map);

Plugin will crash, cause it cannot clone/use some layer that is added by the routing machine.

Leaflet.Draw plugin error

Hi,

I use your print plugin and everything works fine until I added leaflet.draw plugin.
When I draw something, I cant print map.
There was an error in console
TypeError: this._renderer._bounds is undefined

Here is your example code with Leaflet.Draw plugin.

Can you help me solve this issue please?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.