[GIS] How to print Openlayers with base OSM and Geoserver WMS layers

geoserveropenlayers-2printing

I have a map I want to print once the user open some layers.
The layers are geoserver wms and the base layer is OSM.

I know geoserver has printing module (which is installed and working because I get reply from geoserver/pdf/info.json?var=printCapabilities

What I dont understand is how I use it to print the current map with visible layers.

I've looked at GeoExt example (mapfish) but it didn't help me understand.

Update 1 :
I've generated the following URL by code :

http://77.235.53.170/geoserver/pdf/print.pdf?spec={%22units%22:%22degrees%22,%22srs%22:%22EPSG:4326%22,%22layout%22:%22A4%22,%22dpi%22:%22300%22,%22mapTitle%22:%22This%20is%20the%20map%20title%22,%22comment%22:%22This%20is%20the%20map%20comment%22,%22resourcesUrl%22:%20%22http://77.235.53.170/img%22,%22layers%22:[{%22baseURL%22:%22http://77.235.53.170/geoserver/Lehavim/wms%22,%22opacity%22:1,%22singleTile%22:true,%22type%22:%22WMS%22,%22layers%22:[%22%D7%A7%D7%95%20%D7%9E%D7%99%D7%9D%22],%22format%22:%22image/jpeg%22,%22styles%22:[%22%22]}],%22pages%22:[{%22center%22:[3875254.1134954,3680894.557955],%22scale%22:32000,%22rotation%22:0}]}

and I'm getting empty PDF (only with title)…
What could be wrong ?

Best Answer

Geoserver print process involves two steps.

First at the server side, you have to configure your yaml file, called config.yaml. Go through the detailed documentation at MapFish print module documentation page.

Once this done, the second step is for client side. Considering you are using openlayers for your front-end, in order to get the list of visible layers, you will need a simple loop with visibility check, e.g.

var layers = "";
for (var i = 0; i < map.layers.length; i++) {
    if(map.layers[i].visibility == true){
        //get a string of visible layers
        layers = layers + map.layers[i].name + ','
    }
}
//remove the trailing ','
layers = layers.slice(0, -1);

Now you have to pass this to your print url. e.g

var maptitle= "This is the map title";
var mapcomment= "This is the map comment"
var printurl = "http://host:post/geoserver/pdf/print.pdf?spec={"units":"degrees","srs":"EPSG:4326","layout":"A4","dpi":"300","maptitle":"This is the map title","comment":"This is the map comment","resourcesUrl": "http://host:port/img","layers":[{"baseURL":"http://host:port/geoserver/workspace/wms","opacity":1,"singleTile":true,"type":"WMS","layers":["' + layers + '"],"format":"image/jpeg","styles":[""]}],"pages":[{"center":[' + map.getCenter().lon + ',' + map.getCenter().lat + '],"scale":' + getMapScale(Math.ceil(map.getScale())) + ',"rotation":0}]}'

Of course you will have to make relevant changes in the URL. Next assign this URL to your print button and then call a click function pragmatically.

$("#btnprint").attr("href", printUrl);
$('#btnprint')[0].click();

And done!!!

Related Question