It allows you to export an OpenLayers map as a PNG / JPG image or PDF document.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>OpenLayers Map Screenshot</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<style>
#map {
width: 100%;
height: 400px;
}
</style>
</head>
<body>
<button id="export-jpeg-button" type="button"> JPEG</button>
<button id="export-png-button" type="button"> PNG</button>
<button id="export-pdf-button" type="button"> PDF</button>
<div id='map'></div>
</body>
</html>
import 'ol/ol.css';
import Map from 'ol/Map';
import View from 'ol/View';
import TileLayer from 'ol/layer/Tile';
import OSM from 'ol/source/OSM';
import olMapScreenshot from 'ol-map-screenshot';
import '@fortawesome/fontawesome-free/css/all.css';
import 'bootstrap/dist/css/bootstrap.min.css';
import 'bootstrap/dist/js/bootstrap.min.js';
import jsPDF from 'jspdf';
const map = new Map({
layers: [
new TileLayer({
source: new OSM()
})
],
target: 'map',
view: new View({
center: [-531626.1241455, 4563250.0861921],
zoom: 14
})
});
const mapScreenshotParam = {
dim: [190, 160]
};
document.getElementById('export-jpeg-button').onclick = async() => {
mapScreenshotParam.format = "jpeg";
doDonwload('map-screenshot.jpg');
};
document.getElementById('export-png-button').onclick = async() => {
mapScreenshotParam.format = "png";
doDonwload('map-screenshot.png');
};
document.getElementById('export-pdf-button').onclick = async() => {
mapScreenshotParam.format = "jpeg";
const response = await doScreenshot();
createPDFDocument(response);
};
function createPDFDocument(data) {
const pdf = new jsPDF('p', 'mm', 'a4');
pdf.setFont("times");
pdf.setFontSize(16);
pdf.setFontStyle("bold");
const title = "ol-map-screenshop example!";
const pageWidth = pdf.internal.pageSize.getWidth();
pdf.text((pageWidth / 2) - (title.length), 20, title);
pdf.text(pageWidth, 20, title);
pdf.setFontSize(10);
pdf.setFontStyle("italic");
pdf.text(10, 28, "Location: Córdoba, Andalucia, España");
pdf.addImage(data.img, 'JPEG', 10, 30, data.w, data.h);
pdf.save('map-screenshot.pdf');
}
async function doDonwload(fileName) {
const response = await doScreenshot();
const element = document.createElement('a');
element.setAttribute('href', response.img);
element.setAttribute('download', fileName);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
async function doScreenshot() {
try {
return await olMapScreenshot.getScreenshot(map, mapScreenshotParam);
} catch (ex) {
showloader(false);
alert(ex.message);
}
}