• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

geosolutions-it / MapStore2 / 14359153796

09 Apr 2025 02:02PM UTC coverage: 76.955% (-0.03%) from 76.985%
14359153796

Pull #10950

github

web-flow
Merge c89fb6e0a into 3ad831e94
Pull Request #10950: Fix #10947 Updated dockerfile to static files for standard templates

31008 of 48285 branches covered (64.22%)

38489 of 50015 relevant lines covered (76.95%)

35.82 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

89.4
/web/client/plugins/Print.jsx
1
/*
2
 * Copyright 2016, GeoSolutions Sas.
3
 * All rights reserved.
4
 *
5
 * This source code is licensed under the BSD-style license found in the
6
 * LICENSE file in the root directory of this source tree.
7
 */
8

9
import './print/print.css';
10

11
import head from 'lodash/head';
12
import castArray from "lodash/castArray";
13
import isNil from "lodash/isNil";
14
import assign from 'object-assign';
15
import PropTypes from 'prop-types';
16
import React from 'react';
17
import { PanelGroup, Col, Glyphicon, Grid, Panel, Row } from 'react-bootstrap';
18
import { connect } from '../utils/PluginsUtils';
19
import { createSelector } from 'reselect';
20

21
import { setControlProperty, toggleControl } from '../actions/controls';
22
import { configurePrintMap, printError, printSubmit, printSubmitting, addPrintParameter } from '../actions/print';
23
import Message from '../components/I18N/Message';
24
import Dialog from '../components/misc/Dialog';
25
import printReducers from '../reducers/print';
26
import printEpics from '../epics/print';
27
import { printSpecificationSelector } from "../selectors/print";
28
import { layersSelector, rawGroupsSelector } from '../selectors/layers';
29
import { currentLocaleSelector } from '../selectors/locale';
30
import { mapSelector, scalesSelector } from '../selectors/map';
31
import { mapTypeSelector } from '../selectors/maptype';
32
import { normalizeSRS, convertDegreesToRadian } from '../utils/CoordinatesUtils';
33
import { getMessageById } from '../utils/LocaleUtils';
34
import { defaultGetZoomForExtent, getResolutions, mapUpdated, dpi2dpu, DEFAULT_SCREEN_DPI, getScales, reprojectZoom } from '../utils/MapUtils';
35
import { getDerivedLayersVisibility, isInsideResolutionsLimits } from '../utils/LayersUtils';
36
import { has, includes } from 'lodash';
37
import {additionalLayersSelector} from "../selectors/additionallayers";
38
import { MapLibraries } from '../utils/MapTypeUtils';
39

40
/**
41
 * Print plugin. This plugin allows to print current map view. **note**: this plugin requires the  **printing module** to work.
42
 * Please look at mapstore documentation about how to add and configure the printing module in your installation.
43
 *
44
 * It also works as a container for other plugins, usable to customize the UI of the parameters dialog.
45
 *
46
 * The UI supports different targets for adding new plugins:
47
 *  - `left-panel` (controls/widgets to be added to the left column, before the accordion)
48
 *  - `left-panel-accordion` (controls/widgets to be added to the left column, as subpanels of the accordion)
49
 *  - `right-panel` (controls/widgets to be added to the right column, before the buttons bar)
50
 *  - `buttons` (controls/widgets to be added to the right column, in the buttons bar)
51
 *  - `preview-panel` (controls/widgets to be added to the printed pdf preview panel)
52
 *
53
 * In addition it is also possibile to use specific targets that override a standard widget, to replace it
54
 * with a custom one. They are (in order, from left to right and top to bottom in the UI):
55
 *  - `name` (`left-panel`, `position`: `1`)
56
 *  - `description` (`left-panel`, `position`: `2`)
57
 *  - `outputFormat` (`left-panel`, `position`: `3`)
58
 *  - `projection` (`left-panel`, `position`: `4`)
59
 *  - `layout` (`left-panel-accordion`, `position`: `1`)
60
 *  - `legend-options` (`left-panel-accordion`, `position`: `2`)
61
 *  - `resolution` (`right-panel`, `position`: `1`)
62
 *  - `map-preview` (`right-panel`, `position`: `2`)
63
 *  - `default-background-ignore` (`right-panel`, `position`: `3`)
64
 *  - `submit` (`buttons`, `position`: `1`)
65
 *  - `print-preview` (`preview-panel`, `position`: `1`)
66
 *
67
 * To remove a widget, you have to include a Null plugin with the desired target.
68
 * You can use the position to sort existing and custom items.
69
 *
70
 * Standard widgets can be configured by providing an options object as a configuration property
71
 * of this (Print) plugin. The options object of a widget is named `<widget_id>Options`
72
 * (e.g. `outputFormatOptions`).
73
 *
74
 * You can customize Print plugin by creating one custom plugin (or more) that modifies the existing
75
 * components with your own ones. You can configure this plugin in `localConfig.json` as usual.
76
 *
77
 * It delegates to a printingService the creation of the final print. The default printingService
78
 * implements a mapfish-print v2 compatible workflow. It is possible to override the printingService to
79
 * use, via a specific property (printingService).
80
 *
81
 * It is also possible to customize the payload of the spec sent to the mapfish-print engine, by
82
 * adding new transformers to the default chain.
83
 *
84
 * Each transformer is a function that can add / replace / remove fragments from the JSON payload.
85
 *
86
 * @class Print
87
 * @memberof plugins
88
 * @static
89
 *
90
 * @prop {boolean} cfg.useFixedScales if true the printing scale is constrained to the nearest scale of the ones configured
91
 * in the config.yml file, if false the current scale is used
92
 * @prop {object} cfg.overrideOptions overrides print options, this will override options created from current state of map
93
 * @prop {boolean} cfg.overrideOptions.geodetic prints in geodetic mode: in geodetic mode scale calculation is more precise on
94
 * printed maps, but the preview is not accurate
95
 * @prop {string} cfg.overrideOptions.outputFilename name of output file
96
 * @prop {object} cfg.mapPreviewOptions options for the map preview tool
97
 * @prop {string[]} cfg.ignoreLayers list of layer types to ignore in preview and when printing, default ["google", "bing"]
98
 * @prop {boolean} cfg.mapPreviewOptions.enableScalebox if true a combobox to select the printing scale is shown over the preview
99
 * this is particularly useful if useFixedScales is also true, to show the real printing scales
100
 * @prop {boolean} cfg.mapPreviewOptions.enableRefresh true by default, if false the preview is not updated if the user pans or zooms the main map
101
 * @prop {object} cfg.outputFormatOptions options for the output formats
102
 * @prop {object[]} cfg.outputFormatOptions.allowedFormats array of allowed formats, e.g. [{"name": "PDF", "value": "pdf"}]
103
 * @prop {object} cfg.projectionOptions options for the projections
104
 * @prop {string[]} cfg.excludeLayersFromLegend list of layer names e.g. ["workspace:layerName"] to exclude from printed document
105
 * @prop {object} cfg.mergeableParams object to pass to mapfish-print v2 to merge params, example here https://github.com/mapfish/mapfish-print-v2/blob/main/docs/protocol.rst#printpdf
106
 * @prop {object[]} cfg.projectionOptions.projections array of available projections, e.g. [{"name": "EPSG:3857", "value": "EPSG:3857"}]
107
 * @prop {object} cfg.overlayLayersOptions options for overlay layers
108
 * @prop {boolean} cfg.overlayLayersOptions.enabled if true a checkbox will be shown to exclude or include overlay layers to the print
109
 *
110
 * @example
111
 * // printing in geodetic mode
112
 * {
113
 *   "name": "Print",
114
 *   "cfg": {
115
 *       "overrideOptions": {
116
 *          "geodetic": true
117
 *       }
118
 *    }
119
 * }
120
 *
121
 * @example
122
 * // Using a list of fixed scales with scale selector
123
 * {
124
 *   "name": "Print",
125
 *   "cfg": {
126
 *       "ignoreLayers": ["google", "bing"],
127
 *       "useFixedScales": true,
128
 *       "mapPreviewOptions": {
129
 *          "enableScalebox": true
130
 *       }
131
 *    }
132
 * }
133
 *
134
 * @example
135
 * // restrict allowed output formats
136
 * {
137
 *   "name": "Print",
138
 *   "cfg": {
139
 *       "outputFormatOptions": {
140
 *          "allowedFormats": [{"name": "PDF", "value": "pdf"}, {"name": "PNG", "value": "png"}]
141
 *       }
142
 *    }
143
 * }
144
 *
145
 * @example
146
 * // enable custom projections for printing
147
 * "projectionDefs": [{
148
 *    "code": "EPSG:23032",
149
 *    "def": "+proj=utm +zone=32 +ellps=intl +towgs84=-87,-98,-121,0,0,0,0 +units=m +no_defs",
150
 *    "extent": [-1206118.71, 4021309.92, 1295389.0, 8051813.28],
151
 *    "worldExtent": [-9.56, 34.88, 31.59, 71.21]
152
 * }]
153
 * ...
154
 * {
155
 *   "name": "Print",
156
 *   "cfg": {
157
 *       "projectionOptions": {
158
 *          "projections": [{"name": "UTM32N", "value": "EPSG:23032"}, {"name": "EPSG:3857", "value": "EPSG:3857"}, {"name": "EPSG:4326", "value": "EPSG:4326"}]
159
 *       }
160
 *    }
161
 * }
162
 *
163
 * @example
164
 * // customize the printing UI via plugin(s)
165
 * import React from "react";
166
 * import {createPlugin} from "../../utils/PluginsUtils";
167
 * import { connect } from "react-redux";
168
 *
169
 * const MyCustomPanel = () => <div>Hello, I am a custom component</div>;
170
 *
171
 * const MyCustomLayout = ({sheet}) => <div>Hello, I am a custom layout, the sheet is {sheet}</div>;
172
 * const MyConnectedCustomLayout = connect((state) => ({sheet: state.print?.spec.sheet}))(MyCustomLayout);
173
 *
174
 * export default createPlugin('PrintCustomizations', {
175
 *     component: () => null,
176
 *     containers: {
177
 *         Print: [
178
 *             // this entry add a panel between title and description
179
 *             {
180
 *                 target: "left-panel",
181
 *                 position: 1.5,
182
 *                 component: MyCustomPanel
183
 *             },
184
 *             // this entry replaces the layout panel
185
 *             {
186
 *                 target: "layout",
187
 *                 component: MyConnectedCustomLayout,
188
 *                 title: "MyLayout"
189
 *             },
190
 *             // To remove one component, simply create a component that returns null.
191
 *             {
192
 *                 target: "map-preview",
193
 *                 component: () => null
194
 *             }
195
 *         ]
196
 *     }
197
 * });
198
 * @example
199
 * // adds a transformer to the printingService chain
200
 * import {addTransformer} from "@js/utils/PrintUtils";
201
 *
202
 * addTransformer("mytranform", (state, spec) => Promise.resolve({
203
 *      ...spec,
204
 *      custom: "some value"
205
 * }));
206
 */
207

208
function overrideItem(item, overrides = []) {
×
209
    const replacement = overrides.find(i => i.target === item.id);
710✔
210
    return replacement ?? item;
710✔
211
}
212

213
const EmptyComponent = () => {
1✔
214
    return null;
×
215
};
216

217
function handleRemoved(item) {
218
    return item.plugin ? item : {
710!
219
        ...item,
220
        plugin: EmptyComponent
221
    };
222
}
223

224
function mergeItems(standard, overrides) {
225
    return standard
238✔
226
        .map(item => overrideItem(item, overrides))
710✔
227
        .map(handleRemoved);
228
}
229

230
function filterLayer(layer = {}) {
×
231
    // Skip layer with error and type cog
232
    return !layer.loadingError && layer.type !== "cog";
35✔
233
}
234

235
export default {
236
    PrintPlugin: assign({
237
        loadPlugin: (resolve) => {
238
            Promise.all([
17✔
239
                import('./print/index'),
240
                import('../utils/PrintUtils')
241
            ]).then(([printMod, utilsMod]) => {
242

243
                const {
244
                    standardItems
245
                } = printMod.default;
17✔
246

247
                const {
248
                    getDefaultPrintingService,
249
                    getLayoutName,
250
                    getPrintScales,
251
                    getNearestZoom
252
                } = utilsMod;
17✔
253
                class Print extends React.Component {
254
                    static propTypes = {
17✔
255
                        map: PropTypes.object,
256
                        layers: PropTypes.array,
257
                        capabilities: PropTypes.object,
258
                        printSpec: PropTypes.object,
259
                        printSpecTemplate: PropTypes.object,
260
                        withContainer: PropTypes.bool,
261
                        withPanelAsContainer: PropTypes.bool,
262
                        open: PropTypes.bool,
263
                        pdfUrl: PropTypes.string,
264
                        title: PropTypes.string,
265
                        style: PropTypes.object,
266
                        mapWidth: PropTypes.number,
267
                        mapType: PropTypes.string,
268
                        alternatives: PropTypes.array,
269
                        toggleControl: PropTypes.func,
270
                        onBeforePrint: PropTypes.func,
271
                        setPage: PropTypes.func,
272
                        onPrint: PropTypes.func,
273
                        printError: PropTypes.func,
274
                        configurePrintMap: PropTypes.func,
275
                        getLayoutName: PropTypes.func,
276
                        error: PropTypes.string,
277
                        getZoomForExtent: PropTypes.func,
278
                        minZoom: PropTypes.number,
279
                        maxZoom: PropTypes.number,
280
                        usePreview: PropTypes.bool,
281
                        mapPreviewOptions: PropTypes.object,
282
                        syncMapPreview: PropTypes.bool,
283
                        useFixedScales: PropTypes.bool,
284
                        scales: PropTypes.array,
285
                        ignoreLayers: PropTypes.array,
286
                        defaultBackground: PropTypes.oneOfType([PropTypes.string, PropTypes.arrayOf(PropTypes.string)]),
287
                        closeGlyph: PropTypes.string,
288
                        submitConfig: PropTypes.object,
289
                        previewOptions: PropTypes.object,
290
                        currentLocale: PropTypes.string,
291
                        overrideOptions: PropTypes.object,
292
                        items: PropTypes.array,
293
                        excludeLayersFromLegend: PropTypes.array,
294
                        mergeableParams: PropTypes.object,
295
                        addPrintParameter: PropTypes.func,
296
                        printingService: PropTypes.object,
297
                        printMap: PropTypes.object
298
                    };
299

300
                    static contextTypes = {
17✔
301
                        messages: PropTypes.object,
302
                        plugins: PropTypes.object,
303
                        loadedPlugins: PropTypes.object
304
                    };
305

306
                    static defaultProps = {
17✔
307
                        withContainer: true,
308
                        withPanelAsContainer: false,
309
                        title: 'print.paneltitle',
310
                        toggleControl: () => {},
311
                        onBeforePrint: () => {},
312
                        setPage: () => {},
313
                        onPrint: () => {},
314
                        configurePrintMap: () => {},
315
                        printSpecTemplate: {},
316
                        excludeLayersFromLegend: [],
317
                        getLayoutName: getLayoutName,
318
                        getZoomForExtent: defaultGetZoomForExtent,
319
                        pdfUrl: null,
320
                        mapWidth: 370,
321
                        mapType: MapLibraries.OPENLAYERS,
322
                        minZoom: 1,
323
                        maxZoom: 23,
324
                        usePreview: true,
325
                        mapPreviewOptions: {
326
                            enableScalebox: false,
327
                            enableRefresh: true
328
                        },
329
                        syncMapPreview: false,      // make it false to prevent map sync
330
                        useFixedScales: false,
331
                        scales: [],
332
                        ignoreLayers: ["google", "bing"],
333
                        defaultBackground: ["osm", "wms", "empty"],
334
                        closeGlyph: "1-close",
335
                        submitConfig: {
336
                            buttonConfig: {
337
                                bsSize: "small",
338
                                bsStyle: "primary"
339
                            },
340
                            glyph: ""
341
                        },
342
                        previewOptions: {
343
                            buttonStyle: "primary"
344
                        },
345
                        style: {},
346
                        currentLocale: 'en-US',
347
                        overrideOptions: {},
348
                        items: [],
349
                        printingService: getDefaultPrintingService(),
350
                        printMap: {}
351
                    };
352
                    constructor(props) {
353
                        super(props);
17✔
354
                        // Calling configurePrintMap here to replace calling in in UNSAFE_componentWillMount
355
                        this.configurePrintMap();
17✔
356
                        this.state = {
17✔
357
                            activeAccordionPanel: 0
358
                        };
359
                    }
360

361
                    UNSAFE_componentWillReceiveProps(nextProps) {
362
                        const hasBeenOpened = nextProps.open && !this.props.open;
44✔
363
                        const mapHasChanged = this.props.open && this.props.syncMapPreview && mapUpdated(this.props.map, nextProps.map);
44!
364
                        const specHasChanged = (
365
                            nextProps.printSpec.defaultBackground !== this.props.printSpec.defaultBackground ||
44✔
366
                                nextProps.printSpec.additionalLayers !== this.props.printSpec.additionalLayers
367
                        );
368
                        if (hasBeenOpened || mapHasChanged || specHasChanged) {
44✔
369
                            this.configurePrintMap(nextProps);
1✔
370
                        }
371
                    }
372

373
                    getAlternativeBackground = (layers, defaultBackground, projection) => {
17✔
374
                        const allowedBackground = head(castArray(defaultBackground).map(type => ({
10✔
375
                            type
376
                        })).filter(l => this.isAllowed(l, projection)));
10✔
377
                        if (allowedBackground) {
5!
378
                            return head(layers.filter(l => l.type === allowedBackground.type));
5✔
379
                        }
380
                        return null;
×
381
                    };
382

383
                    getItems = (target) => {
17✔
384
                        const filtered = this.props.items.filter(i => !target || i.target === target);
238✔
385
                        const merged = mergeItems(standardItems[target], this.props.items)
238✔
386
                            .map(item => ({
710✔
387
                                ...item,
388
                                target
389
                            }));
390
                        return [...merged, ...filtered]
238✔
391
                            .sort((i1, i2) => (i1.position ?? 0) - (i2.position ?? 0));
496✔
392
                    };
393
                    getMapConfiguration = () => {
17✔
394
                        const map = this.props.printingService.getMapConfiguration();
67✔
395
                        return {
67✔
396
                            ...map,
397
                            layers: this.filterLayers(map.layers, this.props.useFixedScales ? map.scaleZoom : map.zoom, map.projection)
67✔
398
                        };
399
                    };
400
                    getMapSize = (layout) => {
17✔
401
                        const currentLayout = layout || this.getLayout();
59!
402
                        return {
59✔
403
                            width: this.props.mapWidth,
404
                            height: currentLayout && currentLayout.map.height / currentLayout.map.width * this.props.mapWidth || 270
118!
405
                        };
406
                    };
407
                    getPreviewResolution = (zoom, projection) => {
17✔
408
                        const dpu = dpi2dpu(DEFAULT_SCREEN_DPI, projection);
67✔
409
                        const roundZoom = Math.round(zoom);
67✔
410
                        const scale = this.props.useFixedScales
67✔
411
                            ? getPrintScales(this.props.capabilities)[roundZoom]
412
                            : this.props.scales[roundZoom];
413
                        return scale / dpu;
67✔
414
                    };
415
                    getLayout = (props) => {
17✔
416
                        const { getLayoutName: getLayoutNameProp, printSpec, capabilities } = props || this.props;
59✔
417
                        const layoutName = getLayoutNameProp(printSpec);
59✔
418
                        return head(capabilities.layouts.filter((l) => l.name === layoutName));
59✔
419
                    };
420

421
                    renderWarning = (layout) => {
17✔
422
                        if (!layout) {
59!
423
                            return <Row><Col xs={12}><div className="print-warning"><span><Message msgId="print.layoutWarning"/></span></div></Col></Row>;
×
424
                        }
425
                        return null;
59✔
426
                    };
427
                    renderItem = (item, opts) => {
17✔
428
                        const {validations, ...options } = opts;
716✔
429
                        const Comp = item.component ?? item.plugin;
716✔
430
                        const {style, ...other} = this.props;
716✔
431
                        const itemOptions = this.props[item.id + "Options"];
716✔
432
                        return <Comp role="body" {...other} {...item.cfg} {...options} {...itemOptions} validation={validations?.[item.id ?? item.name]}/>;
716✔
433
                    };
434
                    renderItems = (target, options) => {
17✔
435
                        return this.getItems(target)
179✔
436
                            .map(item => this.renderItem(item, options));
598✔
437
                    };
438
                    renderAccordion = (target, options) => {
17✔
439
                        const items = this.getItems(target);
59✔
440
                        return (<PanelGroup accordion activeKey={this.state.activeAccordionPanel} onSelect={(key) => {
59✔
441
                            this.setState({
×
442
                                activeAccordionPanel: key
443
                            });
444
                        }}>
445
                            {items.map((item, pos) => (
446
                                <Panel header={getMessageById(this.context.messages, item.cfg?.title ?? item.title ?? "")} eventKey={pos} collapsible>
118!
447
                                    {this.renderItem(item, options)}
448
                                </Panel>
449
                            ))}
450
                        </PanelGroup>);
451
                    };
452
                    renderPrintPanel = () => {
17✔
453
                        const layout = this.getLayout();
59✔
454
                        const map = this.getMapConfiguration();
59✔
455
                        const options = {
59✔
456
                            layout,
457
                            map,
458
                            layoutName: this.props.getLayoutName(this.props.printSpec),
459
                            mapSize: this.getMapSize(layout),
460
                            resolutions: getResolutions(map?.projection),
461
                            onRefresh: () => this.configurePrintMap(),
×
462
                            notAllowedLayers: this.isBackgroundIgnored(this.props.layers, map?.projection),
463
                            actionConfig: this.props.submitConfig,
464
                            validations: this.props.printingService.validate(),
465
                            rotation: !isNil(this.props.printSpec.rotation) ? convertDegreesToRadian(Number(this.props.printSpec.rotation)) : 0,
59!
466
                            actions: {
467
                                print: this.print,
468
                                addParameter: this.addParameter
469
                            }
470
                        };
471
                        return (
59✔
472
                            <Grid fluid role="body">
473
                                {this.renderError()}
474
                                {this.renderWarning(layout)}
475
                                <Row>
476
                                    <Col xs={12} md={6}>
477
                                        {this.renderItems("left-panel", options)}
478
                                        {this.renderAccordion("left-panel-accordion", options)}
479
                                    </Col>
480
                                    <Col xs={12} md={6} style={{textAlign: "center"}}>
481
                                        {this.renderItems("right-panel", options)}
482
                                        {this.renderItems("buttons", options)}
483
                                        {this.renderDownload()}
484
                                    </Col>
485
                                </Row>
486
                            </Grid>
487
                        );
488
                    };
489

490
                    renderDownload = () => {
17✔
491
                        if (this.props.pdfUrl && !this.props.usePreview) {
59!
492
                            return <iframe src={this.props.pdfUrl} style={{visibility: "hidden", display: "none"}}/>;
×
493
                        }
494
                        return null;
59✔
495
                    };
496

497
                    renderError = () => {
17✔
498
                        if (this.props.error) {
59✔
499
                            return <Row><Col xs={12}><div className="print-error"><span>{this.props.error}</span></div></Col></Row>;
2✔
500
                        }
501
                        return null;
57✔
502
                    };
503

504
                    renderPreviewPanel = () => {
17✔
505
                        return this.renderItems("preview-panel", this.props.previewOptions);
2✔
506
                    };
507

508
                    renderBody = () => {
17✔
509
                        if (this.props.pdfUrl && this.props.usePreview) {
61✔
510
                            return this.renderPreviewPanel();
2✔
511
                        }
512
                        return this.renderPrintPanel();
59✔
513
                    };
514

515
                    render() {
516
                        if ((this.props.capabilities || this.props.error) && this.props.open) {
61!
517
                            if (this.props.withContainer) {
61!
518
                                if (this.props.withPanelAsContainer) {
61!
519
                                    return (<Panel className="mapstore-print-panel" header={<span><span className="print-panel-title"><Message msgId="print.paneltitle"/></span><span className="print-panel-close panel-close" onClick={this.props.toggleControl}></span></span>} style={this.props.style}>
×
520
                                        {this.renderBody()}
521
                                    </Panel>);
522
                                }
523
                                return (<Dialog start={{x: 0, y: 80}} id="mapstore-print-panel" style={{ zIndex: 1990, ...this.props.style}}>
61✔
524
                                    <span role="header"><span className="print-panel-title"><Message msgId="print.paneltitle"/></span><button onClick={this.props.toggleControl} className="print-panel-close close">{this.props.closeGlyph ? <Glyphicon glyph={this.props.closeGlyph}/> : <span>×</span>}</button></span>
61!
525
                                    {this.renderBody()}
526
                                </Dialog>);
527
                            }
528
                            return this.renderBody();
×
529
                        }
530
                        return null;
×
531
                    }
532
                    addParameter = (name, value) => {
17✔
533
                        this.props.addPrintParameter("params." + name, value);
3✔
534
                    };
535
                    isCompatibleWithSRS = (projection, layer) => {
17✔
536
                        return projection === "EPSG:3857" || includes([
44!
537
                            "wms",
538
                            "wfs",
539
                            "vector",
540
                            "graticule",
541
                            "empty",
542
                            "arcgis"
543
                        ], layer.type) || layer.type === "wmts" && has(layer.allowedSRS, projection);
544
                    };
545
                    isAllowed = (layer, projection) => {
17✔
546
                        return this.props.ignoreLayers.indexOf(layer.type) === -1 &&
47✔
547
                            this.isCompatibleWithSRS(normalizeSRS(projection), layer);
548
                    };
549

550
                    isBackgroundIgnored = (layers, projection) => {
17✔
551
                        const background = head((layers || this.props.layers)
126!
552
                            .filter(layer => layer.group === "background" && layer.visibility && this.isAllowed(layer, projection)));
77!
553
                        return !background;
126✔
554
                    };
555
                    filterLayers = (layers, zoom, projection) => {
17✔
556
                        const resolution = this.getPreviewResolution(zoom, projection);
67✔
557

558
                        const filtered = layers.filter((layer) =>
67✔
559
                            layer.visibility &&
42✔
560
                            isInsideResolutionsLimits(layer, resolution) &&
561
                            this.isAllowed(layer, projection)
562
                        );
563
                        if (this.isBackgroundIgnored(layers, projection) && this.props.defaultBackground && this.props.printSpec.defaultBackground) {
67✔
564
                            const defaultBackground = this.getAlternativeBackground(layers, this.props.defaultBackground);
5✔
565
                            if (defaultBackground) {
5!
566
                                return [{
×
567
                                    ...defaultBackground,
568
                                    visibility: true
569
                                }, ...filtered];
570
                            }
571
                            return filtered;
5✔
572
                        }
573
                        return filtered;
62✔
574
                    };
575

576
                    configurePrintMap = (props) => {
17✔
577
                        const {
578
                            map: newMap,
579
                            capabilities,
580
                            configurePrintMap: configurePrintMapProp,
581
                            useFixedScales,
582
                            currentLocale,
583
                            layers,
584
                            printMap,
585
                            printSpec
586
                        } = props || this.props;
18✔
587
                        if (newMap && newMap.bbox && capabilities) {
18!
588
                            const selectedPrintProjection = (printSpec && printSpec?.params?.projection) || (printSpec && printSpec?.projection) || (printMap && printMap.projection) || 'EPSG:3857';
18!
589
                            const printSrs = normalizeSRS(selectedPrintProjection);
18✔
590
                            const mapProjection = newMap.projection;
18✔
591
                            const mapSrs = normalizeSRS(mapProjection);
18✔
592
                            const zoom = reprojectZoom(newMap.zoom, mapSrs, printSrs);
18✔
593
                            const scales = getPrintScales(capabilities);
18✔
594
                            const printMapScales = getScales(printSrs);
18✔
595
                            const scaleZoom = getNearestZoom(zoom, scales, printMapScales);
18✔
596
                            if (useFixedScales) {
18✔
597
                                const scale = scales[scaleZoom];
4✔
598
                                configurePrintMapProp(newMap.center, zoom, scaleZoom, scale,
4✔
599
                                    layers, newMap.projection, currentLocale, useFixedScales);
600
                            } else {
601
                                const scale = printMapScales[zoom];
14✔
602
                                configurePrintMapProp(newMap.center, zoom, scaleZoom, scale,
14✔
603
                                    layers, newMap.projection, currentLocale, useFixedScales);
604
                            }
605
                        }
606
                    };
607

608
                    print = () => {
17✔
609
                        this.props.setPage(0);
8✔
610
                        this.props.onBeforePrint();
8✔
611
                        this.props.printingService.print({
8✔
612
                            excludeLayersFromLegend: this.props.excludeLayersFromLegend,
613
                            mergeableParams: this.props.mergeableParams,
614
                            layers: this.getMapConfiguration()?.layers,
615
                            scales: this.props.useFixedScales ? getPrintScales(this.props.capabilities) : undefined,
8✔
616
                            bbox: this.props.map?.bbox
617
                        })
618
                            .then((spec) =>
619
                                this.props.onPrint(this.props.capabilities.createURL, { ...spec, ...this.props.overrideOptions })
6✔
620
                            )
621
                            .catch(e => {
622
                                this.props.printError("Error in printing:" + e.message);
×
623
                            });
624
                    };
625
                }
626

627
                const selector = createSelector([
17✔
628
                    (state) => state.controls.print && state.controls.print.enabled || state.controls.toolbar && state.controls.toolbar.active === 'print',
61!
629
                    (state) => state.print && state.print.capabilities,
61✔
630
                    printSpecificationSelector,
631
                    (state) => state.print && state.print.pdfUrl,
61✔
632
                    (state) => state.print && state.print.error,
61✔
633
                    mapSelector,
634
                    layersSelector,
635
                    additionalLayersSelector,
636
                    scalesSelector,
637
                    (state) => state.browser && (!state.browser.ie || state.browser.ie11),
61!
638
                    currentLocaleSelector,
639
                    mapTypeSelector,
640
                    (state) => state.print.map,
61✔
641
                    rawGroupsSelector
642
                ], (open, capabilities, printSpec, pdfUrl, error, map, layers, additionalLayers, scales, usePreview, currentLocale, mapType, printMap, groups) => ({
61✔
643
                    open,
644
                    capabilities,
645
                    printSpec,
646
                    pdfUrl,
647
                    error,
648
                    map,
649
                    layers: [
650
                        ...getDerivedLayersVisibility(layers, groups).filter(filterLayer),
651
                        ...(printSpec?.additionalLayers ? additionalLayers.map(l => l.options).filter(
×
652
                            l => {
653
                                const isVector = l.type === 'vector';
×
654
                                const hasFeatures = Array.isArray(l.features) && l.features.length > 0;
×
655
                                return !l.loadingError && (!isVector || (isVector && hasFeatures));
×
656
                            }
657
                        ) : [])
658
                    ],
659
                    scales,
660
                    usePreview,
661
                    currentLocale,
662
                    mapType,
663
                    printMap
664
                }));
665

666
                const PrintPlugin = connect(selector, {
17✔
667
                    toggleControl: toggleControl.bind(null, 'print', null),
668
                    onPrint: printSubmit,
669
                    printError: printError,
670
                    onBeforePrint: printSubmitting,
671
                    setPage: setControlProperty.bind(null, 'print', 'currentPage'),
672
                    configurePrintMap,
673
                    addPrintParameter
674
                })(Print);
675
                resolve(PrintPlugin);
17✔
676
            });
677
        },
678
        enabler: (state) => state.print && state.print.enabled || state.toolbar && state.toolbar.active === 'print'
×
679
    },
680
    {
681
        disablePluginIf: "{state('mapType') === 'cesium' || !state('printEnabled')}",
682
        Toolbar: {
683
            name: 'print',
684
            position: 7,
685
            help: <Message msgId="helptexts.print"/>,
686
            tooltip: "printbutton",
687
            icon: <Glyphicon glyph="print"/>,
688
            exclusive: true,
689
            panel: true,
690
            priority: 1
691
        },
692
        BurgerMenu: {
693
            name: 'print',
694
            position: 2,
695
            tooltip: "printToolTip",
696
            text: <Message msgId="printbutton"/>,
697
            icon: <Glyphicon glyph="print"/>,
698
            action: toggleControl.bind(null, 'print', null),
699
            priority: 3,
700
            doNotHide: true
701
        },
702
        SidebarMenu: {
703
            name: "print",
704
            position: 3,
705
            tooltip: "printbutton",
706
            text: <Message msgId="printbutton"/>,
707
            icon: <Glyphicon glyph="print"/>,
708
            action: toggleControl.bind(null, 'print', null),
709
            doNotHide: true,
710
            toggle: true,
711
            priority: 2
712
        }
713
    }),
714
    reducers: {print: printReducers},
715
    epics: {...printEpics}
716
};
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc