Leveraging Advancements In Openlayers Plugin To Enhance Print Capabilities

Core Problem: Limited Default Print Capabilities

The default print capabilities in OpenLayers are rather limited. Out-of-the-box, users can only print the main map viewport without additional customization. Key elements like map legends, scale bars, north arrows, and titles are not included by default.

Furthermore, the default print output uses the web map resolution and extent. This often results in prints that are not properly scaled or oriented for optimal printing. There is also no way to export prints in various formats like PDF without custom coding.

To unlock the full print potential of OpenLayers maps, developers need to leverage the powerful ol/printing module and features like print templates. Configuring these additional capabilities takes some work but enables truly customizable dynamic prints.

Fundamentals of Print Capabilities in OpenLayers

Understanding OpenLayers’ printing architecture is key to unlocking enhanced capabilities.

The core classes are Print and PrintTemplate. The Print class handles taking a map instance and turning it into a printable output based on a template. PrintTemplate defines the structure, elements, resolution, size, and format of the print output.

By configuring PrintTemplate instances and passing maps to the Print utility, developers can generate fully customized prints in various formats like PDF, PNG, or SVG.

Key Print Template Properties

  • resolution – Output resolution in dots per inch
  • dimensions – Width, height tuple defining paper size
  • layout – Page orientation (portrait or landscape)
  • layers – Map layers to include in print
  • legends – Optional array of legend configs
  • pages – Multi-page settings
  • title – Optional text or element for print title

Configuring these template properties enables full control over print output. The Print utility handles rendering the template with the given map to produce the exported file.

Configuring Map Resolution and Scale for Printing

One major limitation of the default OpenLayers print function is that it uses the same resolution and extent as the interactive web map. This leads to prints without optimal scaling or detail levels.

By configuring the print template’s resolution property, developers can properly size maps for printed output in dots per inch (DPI):


  var printTemplate = new PrintTemplate({
    resolution: 150 // 150 DPI for quality print output
  });

Maps should be exported at ~150 DPI to maintain detail and sharpness when physically printed. Configuring this resolution produces prints appropriately sized for printing versus screen display.

Beyond resolution, the printable map extent can be customized using Print options:


  var printOptions = {
    area: featuresExtent, // custom print extent
    scale: 50000 // custom print scale
  }  

  var pdf = new Print({
    template: printTemplate
  }).print(map, printOptions);

This prints the map at 50,000:1 scale and constrained to the bounding extent of certain features. Combined control over resolution, extent, and scale enables properly sized printable maps.

Setting Optimal Page Size and Orientation

The media size and layout orientation are also vital print settings controlled within print templates.

Standard paper dimensions can be set via the dimensions property. Common sizes include:

  • Letter – 8.5 x 11 inches
  • Legal – 8.5 x 14 inches
  • Tabloid – 11 x 17 inches
  • A3 – 297 x 420 mm

Orientation is configured through the layout property:


  var printTemplate = new PrintTemplate({
    dimensions: [16.5, 11], // 16.5 x 11in custom size
    layout: 'portrait'
  });  

Landscape orientation is also common for wide maps. Multi-page prints are possible by defining page sizes and using the pages property.

Match paper size and orientation to the print content for professional results with no clipping or overflow.

Adding Custom Print Title and Legends

Print exports should include proper map elements like titles and legends to aid understanding and fulfillment. By default these are not included.

The print template’s title property can define custom header text:


  title: 'Biodiversity Hotspots' // title text

HTML elements can also populate the title section for richer content.

Legends can be added through the legends template property:


  legends: [
    {
      title: 'Species',
      layers: [speciesLayer] 
    },
    {  
      title: 'Ecoregions',
      layers: [ecoRegionLayer]       
    }
  ]

This prints separate legends for species and ecoregion map layers. Proper legends provide vital context alongside printable maps.

Exporting Maps in Various Formats

By default, OpenLayers only allows printing maps as PNG images. Expanding output formats requires utilizing the print utility’s export capabilities.

Common print formats include:

  • PNG
  • JPEG
  • SVG
  • PDF

These are enabled based on the format option sent to the Print utility:


  var pdfPrint = new Print({ 
    template: printTemplate
  }).print(map, {format: 'PDF'});

The returned output will be a PDF blob containing the printable map. SVG, JPEG, PNG and other formats work similarly.

Support varies across formats, with PDF, SVG, and PNG offering the most robust print capabilities.

Print Templating for Advanced Customization

While print templates handle many core options, further customization requires crafting templates as separate files.

The template file structure combines HTML, CSS, and special template tags:


<div class="title">
  Title: <span>{{title}}</span> 
</div>

<div class="map">
  <img src="{{map}}">
</div>

<ul class="legends">
  {{#legends}}
    <li>{{title}}</li>        
  {{/legends}}
</ul>

Custom elements can be added alongside template variables denoted with double curly brackets.

The template file is loaded via AJAX and assigned to the print utility:


var print = new Print({
  template: 'resources/print-template.html' 
});
  

With a custom template, map prints can include dynamic data, complex styles, and custom branding.

Example Code for Exporting Maps as PDFs

Here is an example code snippet for exporting OpenLayers maps as PDF using a print template:


// Map layers, view, controls etc
var map = new Map({ .. }); 

// Create print template
var template = new PrintTemplate({
  layout: 'portrait',
  format: 'pdf',
  resolution: 150
});

// Print and export as PDF  
var pdfExport = new Print({
  template: template
}).print(map, {
  title: 'My Map',
  legends: [ .. ] 
});

// Open PDF export
var pdfBlob = new Blob([pdfExport], {type: 'application/pdf'});  

window.open(URL.createObjectURL(pdfBlob));

This leverages the print utility to take the map instance and export it as a PDF using the custom template. The PDF blob is opened in a new tab for previewing and saving.

Additional code handles template loading, data binding, custom layers, and more advanced functionality. But this covers the core workflow.

Customizing Print Templates with Dynamic Data

An advantage of external print templates is the ability to bind custom data. The template can include dynamic values using its data context.

For example, linking the print date:

  
<div class="date">
  {{date}}
</div>

And assigning data values:


var print = new Print({
  template: 'template.html',
  data: {
    date: new Date() 
  }
});

The template can also access feature properties from layers:

  
<ul>
  {{#features}}
    <li>{{name}} ({{pop}})</li>  
  {{/features}}
</ul>

And populated like:


print.print(map, {
  features: countryLayer.getFeatures()
});

This advanced functionality allows integrating custom data with map prints, such as statistics, charts, reports, etc that augment the printed map.

Future Advancements to Watch

As OpenLayers expands so will its printing capabilities. Some major improvements on the horizon include:

  • Embedded JavaScript in templates for advanced data binding and styling.
  • Improved widget and element rendering.
  • Streamlined workflow for multiple template pages.
  • Support for additional print formats like docx or xlsx.

Third party plugins will also help push print customization even further.

While OpenLayers printing is already quite capable, future versions promise exciting new functionality to aid broader custom use cases. Conventional prints will improve alongside creative new options like embedding interactive visualizations.

Leave a Reply

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