// 1、安装ol-ext
npm i ol-ext
// 2、在main.js中引入样式
import 'ol-ext/dist/ol-ext.min.css';
// 3、安装jspdf用于导出pdf
npm install jspdf --save
// 4、安装FileSaver.js用于导出数据
npm i file-saver
2 使用PrintDialog控件
2.1 构造函数的参数说明
@param {string} [options.lang=en] control language, default en
@param {string} options.imageType A string indicating the image format, default image/jpeg
@param {number} options.quality Number between 0 and 1 indicating the image quality to use for image formats that use lossy compression such as image/jpeg and image/webp
@param {string} options.orientation Page orientation (landscape/portrait), default guest the best one
@param {boolean} options.immediate force print even if render is not complete, default false
@param {boolean} [options.openWindow=false] open the file in a new window on print
@param {boolean} [options.copy=true] add a copy select option
@param {boolean} [options.print=true] add a print select option
@param {boolean} [options.pdf=true] add a pdf select option
@param {function} [options.saveAs] a function to save the image as blob
@param {*} [options.jsPDF] jsPDF object to save map as pdf
2.2 openlayers中使用
import {
saveAs
} from 'file-saver'
import {
jsPDF
} from "jspdf";
import OlExtPrintDialog from 'ol-ext/control/PrintDialog'
OlExtMap.prototype.addPrintDialog = () => {
const printControl = new OlExtPrintDialog({
lang: "zh",
pdf: true,
openWindow: false,
});
printControl.setSize('A4');
this_.mMap.addControl(printControl);
printControl.on(['print', 'error'], function (e) {
if (e.image) {
if (e.pdf) { // 导出PDF
const pdf = new jsPDF({
orientation: e.print.orientation,
unit: e.print.unit,
format: e.print.size
});
pdf.addImage(e.image, 'JPEG', e.print.position[0], e.print.position[0], e.print.imageWidth, e.print.imageHeight);
pdf.save(e.print.legend ? 'legend.pdf' : 'map.pdf');
} else { // 导出图片
e.canvas.toBlob(function (blob) {
const name = (e.print.legend ? 'legend.' : 'map.') + e.imageType.replace('image/', '');
saveAs(blob, name);
}, e.imageType, e.quality);
}
} else {
console.warn('No canvas to export');
}
});
}