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

geosolutions-it / MapStore2 / 15163566361

21 May 2025 01:31PM UTC coverage: 76.93% (-0.06%) from 76.985%
15163566361

Pull #10950

github

web-flow
Merge 652f28b2c into 1fe44f98a
Pull Request #10950: Fix #10947 Updated dockerfile to static files for standard templates

30980 of 48267 branches covered (64.18%)

38608 of 50186 relevant lines covered (76.93%)

36.22 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
import FlexBox from '../components/layout/FlexBox';
40
import Text from '../components/layout/Text';
41
import Button from '../components/layout/Button';
42

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

211
function overrideItem(item, overrides = []) {
×
212
    const replacement = overrides.find(i => i.target === item.id);
698✔
213
    return replacement ?? item;
698✔
214
}
215

216
const EmptyComponent = () => {
1✔
217
    return null;
×
218
};
219

220
function handleRemoved(item) {
221
    return item.plugin ? item : {
698!
222
        ...item,
223
        plugin: EmptyComponent
224
    };
225
}
226

227
function mergeItems(standard, overrides) {
228
    return standard
234✔
229
        .map(item => overrideItem(item, overrides))
698✔
230
        .map(handleRemoved);
231
}
232

233
function filterLayer(layer = {}) {
×
234
    // Skip layer with error and type cog
235
    return !layer.loadingError && layer.type !== "cog";
33✔
236
}
237

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

246
                const {
247
                    standardItems
248
                } = printMod.default;
17✔
249

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

303
                    static contextTypes = {
17✔
304
                        messages: PropTypes.object,
305
                        plugins: PropTypes.object,
306
                        loadedPlugins: PropTypes.object
307
                    };
308

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

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

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

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

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

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

500
                    renderError = () => {
17✔
501
                        if (this.props.error) {
58✔
502
                            return <Row><Col xs={12}><div className="print-error"><span>{this.props.error}</span></div></Col></Row>;
2✔
503
                        }
504
                        return null;
56✔
505
                    };
506

507
                    renderPreviewPanel = () => {
17✔
508
                        return this.renderItems("preview-panel", this.props.previewOptions);
2✔
509
                    };
510

511
                    renderBody = () => {
17✔
512
                        if (this.props.pdfUrl && this.props.usePreview) {
60✔
513
                            return this.renderPreviewPanel();
2✔
514
                        }
515
                        return this.renderPrintPanel();
58✔
516
                    };
517

518
                    render() {
519
                        if ((this.props.capabilities || this.props.error) && this.props.open) {
60!
520
                            if (this.props.withContainer) {
60!
521
                                if (this.props.withPanelAsContainer) {
60!
522
                                    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}>
×
523
                                        {this.renderBody()}
524
                                    </Panel>);
525
                                }
526
                                return (<Dialog start={{x: 0, y: 80}} id="mapstore-print-panel" style={{ zIndex: 1990, ...this.props.style}}>
60✔
527
                                    <FlexBox role="header" centerChildrenVertically gap="sm">
528
                                        <FlexBox.Fill component={Text} ellipsis fontSize="md" className="print-panel-title _padding-lr-sm">
529
                                            <Message msgId="print.paneltitle"/>
530
                                        </FlexBox.Fill>
531
                                        <Button onClick={this.props.toggleControl} square borderTransparent className="print-panel-close">
532
                                            {this.props.closeGlyph ? <Glyphicon glyph={this.props.closeGlyph}/> : <span>×</span>}
60!
533
                                        </Button>
534
                                    </FlexBox>
535
                                    {this.renderBody()}
536
                                </Dialog>);
537
                            }
538
                            return this.renderBody();
×
539
                        }
540
                        return null;
×
541
                    }
542
                    addParameter = (name, value) => {
17✔
543
                        this.props.addPrintParameter("params." + name, value);
3✔
544
                    };
545
                    isCompatibleWithSRS = (projection, layer) => {
17✔
546
                        return projection === "EPSG:3857" || includes([
42!
547
                            "wms",
548
                            "wfs",
549
                            "vector",
550
                            "graticule",
551
                            "empty",
552
                            "arcgis"
553
                        ], layer.type) || layer.type === "wmts" && has(layer.allowedSRS, projection);
554
                    };
555
                    isAllowed = (layer, projection) => {
17✔
556
                        return this.props.ignoreLayers.indexOf(layer.type) === -1 &&
45✔
557
                            this.isCompatibleWithSRS(normalizeSRS(projection), layer);
558
                    };
559

560
                    isBackgroundIgnored = (layers, projection) => {
17✔
561
                        const background = head((layers || this.props.layers)
124!
562
                            .filter(layer => layer.group === "background" && layer.visibility && this.isAllowed(layer, projection)));
73!
563
                        return !background;
124✔
564
                    };
565
                    filterLayers = (layers, zoom, projection) => {
17✔
566
                        const resolution = this.getPreviewResolution(zoom, projection);
66✔
567

568
                        const filtered = layers.filter((layer) =>
66✔
569
                            layer.visibility &&
40✔
570
                            isInsideResolutionsLimits(layer, resolution) &&
571
                            this.isAllowed(layer, projection)
572
                        );
573
                        if (this.isBackgroundIgnored(layers, projection) && this.props.defaultBackground && this.props.printSpec.defaultBackground) {
66✔
574
                            const defaultBackground = this.getAlternativeBackground(layers, this.props.defaultBackground);
5✔
575
                            if (defaultBackground) {
5!
576
                                return [{
×
577
                                    ...defaultBackground,
578
                                    visibility: true
579
                                }, ...filtered];
580
                            }
581
                            return filtered;
5✔
582
                        }
583
                        return filtered;
61✔
584
                    };
585

586
                    configurePrintMap = (props) => {
17✔
587
                        const {
588
                            map: newMap,
589
                            capabilities,
590
                            configurePrintMap: configurePrintMapProp,
591
                            useFixedScales,
592
                            currentLocale,
593
                            layers,
594
                            printMap,
595
                            printSpec
596
                        } = props || this.props;
18✔
597
                        if (newMap && newMap.bbox && capabilities) {
18!
598
                            const selectedPrintProjection = (printSpec && printSpec?.params?.projection) || (printSpec && printSpec?.projection) || (printMap && printMap.projection) || 'EPSG:3857';
18!
599
                            const printSrs = normalizeSRS(selectedPrintProjection);
18✔
600
                            const mapProjection = newMap.projection;
18✔
601
                            const mapSrs = normalizeSRS(mapProjection);
18✔
602
                            const zoom = reprojectZoom(newMap.zoom, mapSrs, printSrs);
18✔
603
                            const scales = getPrintScales(capabilities);
18✔
604
                            const printMapScales = getScales(printSrs);
18✔
605
                            const scaleZoom = getNearestZoom(zoom, scales, printMapScales);
18✔
606
                            if (useFixedScales) {
18✔
607
                                const scale = scales[scaleZoom];
4✔
608
                                configurePrintMapProp(newMap.center, zoom, scaleZoom, scale,
4✔
609
                                    layers, newMap.projection, currentLocale, useFixedScales);
610
                            } else {
611
                                const scale = printMapScales[zoom];
14✔
612
                                configurePrintMapProp(newMap.center, zoom, scaleZoom, scale,
14✔
613
                                    layers, newMap.projection, currentLocale, useFixedScales);
614
                            }
615
                        }
616
                    };
617

618
                    print = () => {
17✔
619
                        this.props.setPage(0);
8✔
620
                        this.props.onBeforePrint();
8✔
621
                        this.props.printingService.print({
8✔
622
                            excludeLayersFromLegend: this.props.excludeLayersFromLegend,
623
                            mergeableParams: this.props.mergeableParams,
624
                            layers: this.getMapConfiguration()?.layers,
625
                            scales: this.props.useFixedScales ? getPrintScales(this.props.capabilities) : undefined,
8✔
626
                            bbox: this.props.map?.bbox
627
                        })
628
                            .then((spec) =>
629
                                this.props.onPrint(this.props.capabilities.createURL, { ...spec, ...this.props.overrideOptions })
6✔
630
                            )
631
                            .catch(e => {
632
                                this.props.printError("Error in printing:" + e.message);
×
633
                            });
634
                    };
635
                }
636

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

676
                const PrintPlugin = connect(selector, {
17✔
677
                    toggleControl: toggleControl.bind(null, 'print', null),
678
                    onPrint: printSubmit,
679
                    printError: printError,
680
                    onBeforePrint: printSubmitting,
681
                    setPage: setControlProperty.bind(null, 'print', 'currentPage'),
682
                    configurePrintMap,
683
                    addPrintParameter
684
                })(Print);
685
                resolve(PrintPlugin);
17✔
686
            });
687
        },
688
        enabler: (state) => state.print && state.print.enabled || state.toolbar && state.toolbar.active === 'print'
×
689
    },
690
    {
691
        disablePluginIf: "{state('mapType') === 'cesium' || !state('printEnabled')}",
692
        Toolbar: {
693
            name: 'print',
694
            position: 7,
695
            help: <Message msgId="helptexts.print"/>,
696
            tooltip: "printbutton",
697
            icon: <Glyphicon glyph="print"/>,
698
            exclusive: true,
699
            panel: true,
700
            priority: 1
701
        },
702
        BurgerMenu: {
703
            name: 'print',
704
            position: 2,
705
            tooltip: "printToolTip",
706
            text: <Message msgId="printbutton"/>,
707
            icon: <Glyphicon glyph="print"/>,
708
            action: toggleControl.bind(null, 'print', null),
709
            priority: 3,
710
            doNotHide: true
711
        },
712
        SidebarMenu: {
713
            name: "print",
714
            position: 3,
715
            tooltip: "printbutton",
716
            text: <Message msgId="printbutton"/>,
717
            icon: <Glyphicon glyph="print"/>,
718
            action: toggleControl.bind(null, 'print', null),
719
            doNotHide: true,
720
            toggle: true,
721
            priority: 2
722
        }
723
    }),
724
    reducers: {print: printReducers},
725
    epics: {...printEpics}
726
};
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