Printing and export · Angular, React and OpenLayers
Export the map as a PDF
Export the visible OpenLayers map extent to a single-page A5–A0 PDF up to 300 DPI off-screen using cc-openlayers MapRenderer and symbolScale.

What this example shows
Over Kraków’s Old Town with the Main Square outlined, controls below the viewport let you pick a paper size (A5 through A0) and print resolution (72 to 300 DPI) and click Export PDF to download map.pdf matching your exact screen extent and rotation—without resizing or flashing the live map on screen.
When you need it
Planners, engineers and citizens exporting a map for a report or plotter need crisp 150–300 DPI typography and stroke weights on A4/A3 paper while keeping the exact geographic area currently framed on their monitor.
Rendering on a dedicated off-screen MapRenderer avoids the jarring viewport resize flicker and tile-cache thrashing seen in naive DOM-resizing export scripts.
The code
The example uses cc-openlayers, my Angular component library for OpenLayers: each aol-… element creates the OpenLayers object it names, updates it from its inputs and disposes of it with the component.
export-pdf.shared.tsimport {
canvasToJpeg,
createImagePdf,
MapRenderer,
mmToPixels,
mmToPoints,
paperSize,
type PaperName,
} from 'cc-openlayers/print';
import type OlMap from 'ol/Map.js';
/** The page sizes of the form; the larger ones take longer and need more memory. */
export const pageFormats: readonly { value: PaperName; label: string }[] = [
{ value: 'A0', label: 'A0 (slow)' },
{ value: 'A1', label: 'A1' },
{ value: 'A2', label: 'A2' },
{ value: 'A3', label: 'A3' },
{ value: 'A4', label: 'A4' },
{ value: 'A5', label: 'A5 (fast)' },
];
/** The resolutions of the form, in dots per inch. */
export const resolutions: readonly { value: number; label: string }[] = [
{ value: 72, label: '72 dpi (fast)' },
{ value: 150, label: '150 dpi' },
{ value: 300, label: '300 dpi (slow)' },
];
export interface PdfOptions {
readonly format: PaperName;
/** Dots per inch of the picture on the page. */
readonly dpi: number;
}
/**
* A PDF of the extent the map shows, fitted to a landscape page. The picture is drawn on a hidden map of the
* page's size in pixels, so the map on the screen keeps its size and its view.
*/
export async function mapToPdf(map: OlMap, { format, dpi }: PdfOptions): Promise<Uint8Array> {
const [pageWidth, pageHeight] = paperSize(format, 'landscape');
const width = Math.round(mmToPixels(pageWidth, dpi));
const height = Math.round(mmToPixels(pageHeight, dpi));
const size = map.getSize();
if (!size) throw new Error('The map has no size yet.');
const view = map.getView();
// The page shows what the screen shows, so symbols grow with the picture.
const scaling = Math.min(width / size[0], height / size[1]);
const { canvas } = await new MapRenderer(map).render({
size: [width, height],
center: view.getCenter() ?? [0, 0],
resolution: (view.getResolution() ?? 1) / scaling,
rotation: view.getRotation(),
symbolScale: scaling,
background: '#fff',
});
return createImagePdf([
{
width: mmToPoints(pageWidth),
height: mmToPoints(pageHeight),
jpeg: await canvasToJpeg(canvas),
imageWidth: canvas.width,
imageHeight: canvas.height,
},
]);
}
/** Offers the PDF as a file through a temporary object URL, which is revoked in the next task, so the browser can start the download first. */
export function downloadPdf(pdf: Uint8Array, fileName = 'map.pdf'): void {
const url = URL.createObjectURL(new Blob([pdf as BlobPart], { type: 'application/pdf' }));
const link = document.createElement('a');
link.href = url;
link.download = fileName;
link.click();
setTimeout(() => URL.revokeObjectURL(url));
}export-pdf.tsimport { ChangeDetectionStrategy, Component, inject, PendingTasks, signal, viewChild } from '@angular/core';
import {
CoordinateComponent,
DefaultControlComponent,
DefaultInteractionComponent,
FeatureComponent,
LayerTileComponent,
LayerVectorComponent,
MapComponent,
SourceOsmComponent,
SourceVectorComponent,
ViewComponent,
} from 'cc-openlayers';
import type { PaperName } from 'cc-openlayers/print';
import WKT from 'ol/format/WKT';
import { downloadPdf, mapToPdf, pageFormats, resolutions } from './export-pdf.shared';
/**
* Exports the map as a PDF page: the extent on the screen is drawn off-screen at the chosen page size and resolution
* with the print module, so the map on the screen is never resized.
*/
@Component({
selector: 'app-export-pdf',
imports: [
CoordinateComponent,
DefaultControlComponent,
DefaultInteractionComponent,
FeatureComponent,
LayerTileComponent,
LayerVectorComponent,
MapComponent,
SourceOsmComponent,
SourceVectorComponent,
ViewComponent,
],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<aol-map height="480px">
<aol-interaction-default />
<aol-control-defaults />
<aol-view [zoom]="15"><aol-coordinate [x]="19.9368" [y]="50.0614" srid="EPSG:4326" /></aol-view>
<aol-layer-tile><aol-source-osm /></aol-layer-tile>
<aol-layer-vector [opacity]="0.5">
<aol-source-vector>
<aol-feature [geometry]="geometry" />
</aol-source-vector>
</aol-layer-vector>
</aol-map>
<div class="example-controls">
<label>
Page size
<select name="format" (change)="format.set(value($event))">
@for (option of formats; track option.value) {
<option [value]="option.value" [selected]="option.value === format()">{{ option.label }}</option>
}
</select>
</label>
<label>
Resolution
<select name="resolution" (change)="dpi.set(+value($event))">
@for (option of resolutionOptions; track option.value) {
<option [value]="option.value" [selected]="option.value === dpi()">{{ option.label }}</option>
}
</select>
</label>
<button type="button" [disabled]="exporting()" (click)="exportPdf()">Export PDF</button>
</div>
`,
})
export class ExportPdf {
/** The Main Square of Kraków. */
protected readonly geometry = new WKT().readGeometry(
'POLYGON((19.9358 50.0610, 19.9386 50.0610, 19.9386 50.0628, 19.9358 50.0628, 19.9358 50.0610))',
{ dataProjection: 'EPSG:4326', featureProjection: 'EPSG:3857' }
);
protected readonly formats = pageFormats;
protected readonly resolutionOptions = resolutions;
protected readonly format = signal<PaperName>('A4');
protected readonly dpi = signal(72);
protected readonly exporting = signal(false);
private readonly map = viewChild.required(MapComponent);
private readonly pending = inject(PendingTasks);
protected exportPdf(): void {
this.exporting.set(true);
void this.pending.run(async () => {
try {
downloadPdf(await mapToPdf(this.map().instance, { format: this.format(), dpi: this.dpi() }));
} finally {
this.exporting.set(false);
}
});
}
protected value(event: Event): never {
return (event.target as HTMLSelectElement).value as never;
}
} The React version uses the library's React adapter, cc-openlayers/react: each component creates the OpenLayers object it names when it mounts, updates it from its props and disposes of it when it unmounts.
export-pdf.react.tsximport { useRef, useState } from 'react';
import type { PaperName } from 'cc-openlayers/print';
import WKT from 'ol/format/WKT.js';
import type OLMap from 'ol/Map.js';
import {
Coordinate,
DefaultControls,
DefaultInteractions,
Feature,
Map,
OSMSource,
TileLayer,
VectorLayer,
VectorSource,
View,
} from 'cc-openlayers/react';
import { downloadPdf, mapToPdf, pageFormats, resolutions } from './export-pdf.shared';
/** The Main Square of Kraków. */
const geometry = new WKT().readGeometry(
'POLYGON((19.9358 50.0610, 19.9386 50.0610, 19.9386 50.0628, 19.9358 50.0628, 19.9358 50.0610))',
{ dataProjection: 'EPSG:4326', featureProjection: 'EPSG:3857' }
);
/**
* Exports the map as a PDF page: the extent on the screen is drawn off-screen at the chosen page size and resolution
* with the print module, so the map on the screen is never resized.
*/
export function ExportPdf() {
const map = useRef<OLMap>(null);
const [format, setFormat] = useState<PaperName>('A4');
const [dpi, setDpi] = useState(72);
const [exporting, setExporting] = useState(false);
const exportPdf = async () => {
setExporting(true);
try {
downloadPdf(await mapToPdf(map.current as OLMap, { format, dpi }));
} finally {
setExporting(false);
}
};
return (
<>
<Map ref={map} height="480px">
<DefaultInteractions />
<DefaultControls />
<View zoom={15}>
<Coordinate x={19.9368} y={50.0614} srid="EPSG:4326" />
</View>
<TileLayer>
<OSMSource />
</TileLayer>
<VectorLayer opacity={0.5}>
<VectorSource>
<Feature geometry={geometry} />
</VectorSource>
</VectorLayer>
</Map>
<div className="example-controls">
<label>
Page size
<select name="format" value={format} onChange={(event) => setFormat(event.target.value as PaperName)}>
{pageFormats.map((option) => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
</select>
</label>
<label>
Resolution
<select name="resolution" value={dpi} onChange={(event) => setDpi(Number(event.target.value))}>
{resolutions.map((option) => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
</select>
</label>
<button type="button" disabled={exporting} onClick={exportPdf}>
Export PDF
</button>
</div>
</>
);
}export-pdf.shared.tsimport {
canvasToJpeg,
createImagePdf,
MapRenderer,
mmToPixels,
mmToPoints,
paperSize,
type PaperName,
} from 'cc-openlayers/print';
import type OlMap from 'ol/Map.js';
/** The page sizes of the form; the larger ones take longer and need more memory. */
export const pageFormats: readonly { value: PaperName; label: string }[] = [
{ value: 'A0', label: 'A0 (slow)' },
{ value: 'A1', label: 'A1' },
{ value: 'A2', label: 'A2' },
{ value: 'A3', label: 'A3' },
{ value: 'A4', label: 'A4' },
{ value: 'A5', label: 'A5 (fast)' },
];
/** The resolutions of the form, in dots per inch. */
export const resolutions: readonly { value: number; label: string }[] = [
{ value: 72, label: '72 dpi (fast)' },
{ value: 150, label: '150 dpi' },
{ value: 300, label: '300 dpi (slow)' },
];
export interface PdfOptions {
readonly format: PaperName;
/** Dots per inch of the picture on the page. */
readonly dpi: number;
}
/**
* A PDF of the extent the map shows, fitted to a landscape page. The picture is drawn on a hidden map of the
* page's size in pixels, so the map on the screen keeps its size and its view.
*/
export async function mapToPdf(map: OlMap, { format, dpi }: PdfOptions): Promise<Uint8Array> {
const [pageWidth, pageHeight] = paperSize(format, 'landscape');
const width = Math.round(mmToPixels(pageWidth, dpi));
const height = Math.round(mmToPixels(pageHeight, dpi));
const size = map.getSize();
if (!size) throw new Error('The map has no size yet.');
const view = map.getView();
// The page shows what the screen shows, so symbols grow with the picture.
const scaling = Math.min(width / size[0], height / size[1]);
const { canvas } = await new MapRenderer(map).render({
size: [width, height],
center: view.getCenter() ?? [0, 0],
resolution: (view.getResolution() ?? 1) / scaling,
rotation: view.getRotation(),
symbolScale: scaling,
background: '#fff',
});
return createImagePdf([
{
width: mmToPoints(pageWidth),
height: mmToPoints(pageHeight),
jpeg: await canvasToJpeg(canvas),
imageWidth: canvas.width,
imageHeight: canvas.height,
},
]);
}
/** Offers the PDF as a file through a temporary object URL, which is revoked in the next task, so the browser can start the download first. */
export function downloadPdf(pdf: Uint8Array, fileName = 'map.pdf'): void {
const url = URL.createObjectURL(new Blob([pdf as BlobPart], { type: 'application/pdf' }));
const link = document.createElement('a');
link.href = url;
link.download = fileName;
link.click();
setTimeout(() => URL.revokeObjectURL(url));
}How the React version works
The map of Kraków's Main Square exported as a one-page PDF in a chosen page size and resolution. The picture shows the extent on the screen, drawn off-screen at the page's size, so the map on the screen keeps its size while the export runs.
What both versions share
OpenLayers renders the map and handles the interactions; the cc-openlayers/core layer gives both adapters the same view binding (MapViewBinding) and the same conversion of coordinates from EPSG:4326 to the map's projection. Both versions import the page sizes, the resolutions, mapToPdf and downloadPdf from the example's .shared.ts file, so the logic exists once. mapToPdf draws the picture with MapRenderer from cc-openlayers/print, which copies the visible layers onto a hidden map of the page's pixel size, and writes the page with canvasToJpeg and createImagePdf from the same module; no PDF library is needed.
From Angular to React
| Angular | React |
|---|---|
signals of the page size, the resolution and the export in progress | useState |
viewChild.required(MapComponent) and .instance | useRef passed as ref to Map, which holds the ol/Map |
exportPdf() inside PendingTasks.run, try and finally | an async click handler with the same try and finally |
@for over the options with [selected] | map with a key and value on the select |
the polygon read with WKT in a class field | the same polygon as a module constant |
Who creates, updates and disposes
Map creates the ol/Map in useLayoutEffect and disposes of it on unmount; each layer, source and interaction component adds its object to the parent it gets from context and removes it in its effect's cleanup, as ngOnDestroy does in Angular. The hidden map exists only during MapRenderer.render, which creates it and disposes of it in a finally block; the object URL of the file lives until the download has started.
Architecture and OpenLayers mechanics
Wrapped inside Angular PendingTasks (disabling the button while exporting is true), mapToPdf delegates to MapRenderer from cc-openlayers: cloning layers onto a hidden off-screen map sized to the target paper’s pixel dimensions, dividing view resolution by scaling so the screen extent is fitted to the page, with extra ground on the axis that does not limit the fit, and multiplying vector/label sizes by symbolScale so strokes do not turn hairline-thin at 300 DPI.
Zero external PDF libraries are bundled—canvasToJpeg and createImagePdf wrap the rendered JPEG directly into a valid single-page PDF downloaded as map.pdf via downloadPdf.
How it works
mapToPdfusesMapRendererto render the target paper pixel dimensions off-screen at the active centre, rotation andscaling-adjusted resolution.symbolScalescales stroke widths, icons and text proportionally so high-DPI prints match on-screen visual weight.canvasToJpegandcreateImagePdfassemble a valid PDF document with zero third-party PDF bundle dependencies.downloadPdftriggers amap.pdfdownload via a temporary object URL whileexportingandPendingTaskstrack progress.
Pitfalls
- Never resize the user’s visible on-screen map element to 3508 × 2480 px to capture a print—off-screen rendering prevents UI layout jumps and redundant double tile reloads.
- Exporting canvas pixels requires CORS-cleared tiles (
MapRendererconfigures cloned sources for CORS automatically, provided upstream tile servers send CORS headers). - Browser HTML5 canvas implementations cap maximum backing dimensions (desktop browsers allow tens of thousands of pixels per side, mobile Safari far less)—an
A0sheet at 300 DPI (~14,043 × 9,933 px) can therefore fail on phones and tablets, so pair large poster formats with moderate DPI (72–150 DPI).
Related examples
The same feature in the OpenLayers examples .
Background: state and lifecycle of maps in Angular with OpenLayers, which the components of cc-openlayers take care of.