import jsPDF from 'jspdf';
const dims = {
a0: [1189, 841],
a1: [841, 594],
a2: [594, 420],
a3: [420, 297],
a4: [297, 210],
a5: [210, 148],
};
/**
* 设置标题
* @param format 纸张尺寸
* @param resolution resolution
* @param map 地图对象
*/
export default function downLoadPDF(format, resolution, map) {
const dim = dims[format]; //纸张尺寸
console.log(dim);
const width = Math.round((dim[0] * resolution) / 25.4); //DOM宽
const height = Math.round((dim[1] * resolution) / 25.4); //DOM高
const size = map.getSize(); //地图大小
const viewResolution = map.getView().getResolution();
console.log(map.getView());
console.log(viewResolution); //目标分辨率
console.log(map);
map.once('rendercomplete', function () {
//地图加载完成
console.log(111);
console.log('34324234');
const mapCanvas = document.createElement('canvas');
mapCanvas.width = width;
mapCanvas.height = height;
const mapContext = mapCanvas.getContext('2d');
Array.prototype.forEach.call(
document.querySelectorAll('.ol-layer canvas'), //遍历.ol-layer canvas
function (canvas) {
if (canvas.width > 0) {
const opacity = canvas.parentNode.style.opacity; //透明度
mapContext.globalAlpha = opacity === '' ? 1 : Number(opacity); //设置透明度
const transform = canvas.style.transform; //装换
// Get the transform parameters from the style's transform matrix
const matrix = transform
.match(/^matrix\(([^(]*)\)$/)[1]
.split(',')
.map(Number);
// Apply the transform to the export map context
CanvasRenderingContext2D.prototype.setTransform.apply(
mapContext,
matrix
);
mapContext.drawImage(canvas, 0, 0); //绘制
}
}
);
mapContext.globalAlpha = 1;
mapContext.setTransform(1, 0, 0, 1, 0, 0);
const pdf = new jsPDF('landscape', undefined, format);
console.log(mapCanvas);
mapCanvas.toBlob((blob) => {
downloadBlob(blob, 'test.png');
});
pdf.addImage(
mapCanvas.toDataURL('image/jpeg'),
'JPEG',
0,
0,
dim[0],
dim[1]
);
pdf.save('map.pdf');
// Reset original map size
map.setSize(size);
map.getView().setResolution(viewResolution);
document.body.style.cursor = 'auto';
});
// Set print size
const printSize = [width, height];
map.setSize(printSize);
const scaling = Math.min(width / size[0], height / size[1]);
console.log(scaling);
map.getView().setResolution(viewResolution / scaling);
console.log('222');
}
/**
* 下载
* @param blob
* @param fileName
*/
function downloadBlob(blob, fileName) {
const eleLink = document.createElement('a');
eleLink.download = fileName;
eleLink.style.display = 'none';
eleLink.href = URL.createObjectURL(blob);
// 自动触发点击
document.body.appendChild(eleLink);
eleLink.click();
// 然后移除
document.body.removeChild(eleLink);
}