Export Pdf
Runnable OpenLayers example: Export Pdf. Open the live demo, read the complete source, and copy the file into your project. No build step or API key.
single HTML file · CDN dependencies onlyinterface may contain Chinese labels
Source
<!--
示例:地图导出为 PDF — OpenLayers export-pdf
核心逻辑:rendercomplete 后合成各图层 canvas,加标题条,再交给浏览器打印成 PDF
依赖:OpenLayers 10.3.1 · jsDelivr CDN
-->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta name="robots" content="noindex,follow">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>地图导出为 PDF</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/ol@10.3.1/ol.css">
<style>
html,body{height:100%;margin:0}
body{display:flex;flex-direction:column;overflow:hidden;
font:13px/1.6 -apple-system,"Segoe UI","PingFang SC",sans-serif}
.bar{flex:0 0 auto;padding:8px 12px;background:#f6f7f9;border-bottom:1px solid #e3e6ea;
display:flex;gap:10px;align-items:center;font-size:12px;color:#58606e;flex-wrap:wrap}
.bar button{font:inherit;padding:3px 9px;border:1px solid #ccd2da;background:#fff;
border-radius:3px;cursor:pointer;color:#2b3140}
#map{flex:1 1 auto;min-height:0;background:#eef0f3}
</style>
</head>
<body>
<div class="bar">
<button id="export">导出 A4 版式</button>
<span id="info">导出后在新窗口按 Ctrl+P 选择「另存为 PDF」</span>
</div>
<div id="map"></div>
<script src="https://cdn.jsdelivr.net/npm/ol@10.3.1/dist/ol.js"></script>
<script>
(function () {
'use strict';
if (typeof ol === 'undefined') {
document.getElementById('map').innerHTML =
'<div style="padding:20px;color:#b42318">OpenLayers 加载失败,请检查能否访问 cdn.jsdelivr.net</div>';
return;
}
var infoEl = document.getElementById('info');
var points = [
[116.391263, 39.907359, '天安门'],
[116.410600, 39.914700, '王府井'],
[116.374200, 39.909700, '西单'],
[116.438400, 39.916900, '东单']
].map(function (p) {
return new ol.Feature({
geometry: new ol.geom.Point(ol.proj.fromLonLat([p[0], p[1]])),
name: p[2]
});
});
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({ source: new ol.source.XYZ({url: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}', attributions: 'Tiles © Esri'}) }),
new ol.layer.Vector({
source: new ol.source.Vector({ features: points }),
style: function (feature) {
return new ol.style.Style({
image: new ol.style.Circle({
radius: 5,
fill: new ol.style.Fill({ color: '#1f5fd0' }),
stroke: new ol.style.Stroke({ color: '#fff', width: 2 })
}),
text: new ol.style.Text({
text: feature.get('name'),
offsetY: -13,
font: '500 12px sans-serif',
fill: new ol.style.Fill({ color: '#16181d' }),
stroke: new ol.style.Stroke({ color: '#fff', width: 3 })
})
});
}
})
],
view: new ol.View({
center: ol.proj.fromLonLat([116.391, 39.907]),
zoom: 13,
minZoom: 2
}),
controls: ol.control.defaults.defaults({ attribution: false })
});
/* A4 横向 96dpi 约 1123 × 794 像素 */
var PAGE_W = 1123;
var PAGE_H = 794;
var TITLE_H = 72;
document.getElementById('export').addEventListener('click', function () {
infoEl.textContent = '正在合成图层…';
map.once('rendercomplete', function () {
var mapSize = map.getSize();
var canvas = document.createElement('canvas');
canvas.width = PAGE_W;
canvas.height = PAGE_H;
var ctx = canvas.getContext('2d');
ctx.fillStyle = '#ffffff';
ctx.fillRect(0, 0, PAGE_W, PAGE_H);
/* 逐层绘制,保留图层透明度 */
var layers = map.getViewport().querySelectorAll('.ol-layer');
Array.prototype.forEach.call(layers, function (el) {
var layerCanvas = el.querySelector('canvas');
if (!layerCanvas) return;
var opacity = parseFloat(el.style.opacity || '1');
ctx.globalAlpha = isNaN(opacity) ? 1 : opacity;
ctx.drawImage(layerCanvas, 0, TITLE_H, PAGE_W, PAGE_H - TITLE_H);
});
ctx.globalAlpha = 1;
/* 标题与比例尺说明条 */
ctx.fillStyle = '#16181d';
ctx.font = '600 22px "PingFang SC","Microsoft YaHei",sans-serif';
ctx.fillText('北京市中心城区要素分布', 40, 44);
ctx.fillStyle = '#58606e';
ctx.font = '13px "PingFang SC","Microsoft YaHei",sans-serif';
var view = map.getView();
var res = view.getResolution();
ctx.fillText(
'中心 ' + ol.proj.toLonLat(view.getCenter()).map(function (v) {
return v.toFixed(5);
}).join(', ') + ' 分辨率 ' + res.toFixed(2) + ' m/px ' +
mapSize[0] + ' × ' + mapSize[1] + ' 画布',
40, 64
);
var url = canvas.toDataURL('image/png');
var win = window.open('', '_blank');
if (!win) {
infoEl.textContent = '浏览器拦截了新窗口,请允许弹窗后重试';
return;
}
win.document.write(
'<!DOCTYPE html><html><head>
<meta name="robots" content="noindex,follow"><meta charset="utf-8"><title>地图导出</title>' +
'<style>@page{size:A4 landscape;margin:0}' +
'body{margin:0;font-family:sans-serif}' +
'img{width:100%;display:block}' +
'.hint{padding:10px 16px;color:#58606e;font-size:13px}</style></head><body>' +
'<img src="' + url + '">' +
'<p class="hint">按 Ctrl+P 选择「另存为 PDF」,纸张设为 A4 横向、边距为零即可得到单页 PDF。</p>' +
'</body></html>'
);
win.document.close();
infoEl.textContent = '已生成 ' + PAGE_W + ' × ' + PAGE_H + ' 版式,可在新窗口打印';
});
/* 触发一次同步渲染,让 rendercomplete 必定到来 */
map.renderSync();
});
})();
</script>
</body>
</html>
Language: the code and this page are in English; the full tutorial and API notes for this example are in Chinese. The demo itself is the authoritative version — it runs exactly as shown.