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.

OpenStreetMap of the Old Town of Kraków with the Main Square outlined, and below the map the page size A4, the resolution 72 dpi and the Export PDF button.
A screenshot of the example. Map data © OpenStreetMap contributors.

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.ts
import {
  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.ts
import { 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;
  }
}

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

  • mapToPdf uses MapRenderer to render the target paper pixel dimensions off-screen at the active centre, rotation and scaling-adjusted resolution.
  • symbolScale scales stroke widths, icons and text proportionally so high-DPI prints match on-screen visual weight.
  • canvasToJpeg and createImagePdf assemble a valid PDF document with zero third-party PDF bundle dependencies.
  • downloadPdf triggers a map.pdf download via a temporary object URL while exporting and PendingTasks track 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 (MapRenderer configures 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 A0 sheet 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).

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.