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

geosolutions-it / MapStore2 / 15180837196

22 May 2025 07:35AM UTC coverage: 76.882% (-0.05%) from 76.934%
15180837196

Pull #11130

github

web-flow
Merge 838d482a3 into 94d9822b2
Pull Request #11130: #10839: Allow printing by freely setting the scale factor

31033 of 48379 branches covered (64.15%)

40 of 84 new or added lines in 9 files covered. (47.62%)

4 existing lines in 3 files now uncovered.

38641 of 50260 relevant lines covered (76.88%)

36.34 hits per line

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

89.24
/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
import { getResolutionMultiplier } from '../utils/PrintUtils';
43

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

215
function overrideItem(item, overrides = []) {
×
216
    const replacement = overrides.find(i => i.target === item.id);
746✔
217
    return replacement ?? item;
746✔
218
}
219

220
const EmptyComponent = () => {
1✔
221
    return null;
×
222
};
223

224
function handleRemoved(item) {
225
    return item.plugin ? item : {
746!
226
        ...item,
227
        plugin: EmptyComponent
228
    };
229
}
230

231
function mergeItems(standard, overrides) {
232
    return standard
250✔
233
        .map(item => overrideItem(item, overrides))
746✔
234
        .map(handleRemoved);
235
}
236

237
function filterLayer(layer = {}) {
×
238
    // Skip layer with error and type cog
239
    return !layer.loadingError && layer.type !== "cog";
33✔
240
}
241

242
export default {
243
    PrintPlugin: assign({
244
        loadPlugin: (resolve) => {
245
            Promise.all([
18✔
246
                import('./print/index'),
247
                import('../utils/PrintUtils')
248
            ]).then(([printMod, utilsMod]) => {
249

250
                const {
251
                    standardItems
252
                } = printMod.default;
18✔
253

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

307
                    static contextTypes = {
18✔
308
                        messages: PropTypes.object,
309
                        plugins: PropTypes.object,
310
                        loadedPlugins: PropTypes.object
311
                    };
312

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

369
                    UNSAFE_componentWillReceiveProps(nextProps) {
370
                        const hasBeenOpened = nextProps.open && !this.props.open;
46✔
371
                        const mapHasChanged = this.props.open && this.props.syncMapPreview && mapUpdated(this.props.map, nextProps.map);
46!
372
                        const specHasChanged = (
373
                            nextProps.printSpec.defaultBackground !== this.props.printSpec.defaultBackground ||
46✔
374
                                nextProps.printSpec.additionalLayers !== this.props.printSpec.additionalLayers
375
                        );
376
                        if (hasBeenOpened || mapHasChanged || specHasChanged) {
46✔
377
                            this.configurePrintMap(nextProps);
1✔
378
                        }
379
                    }
380

381
                    getAlternativeBackground = (layers, defaultBackground, projection) => {
18✔
382
                        const allowedBackground = head(castArray(defaultBackground).map(type => ({
10✔
383
                            type
384
                        })).filter(l => this.isAllowed(l, projection)));
10✔
385
                        if (allowedBackground) {
5!
386
                            return head(layers.filter(l => l.type === allowedBackground.type));
5✔
387
                        }
388
                        return null;
×
389
                    };
390

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

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

498
                    renderDownload = () => {
18✔
499
                        if (this.props.pdfUrl && !this.props.usePreview) {
62!
500
                            return <iframe src={this.props.pdfUrl} style={{visibility: "hidden", display: "none"}}/>;
×
501
                        }
502
                        return null;
62✔
503
                    };
504

505
                    renderError = () => {
18✔
506
                        if (this.props.error) {
62✔
507
                            return <Row><Col xs={12}><div className="print-error"><span>{this.props.error}</span></div></Col></Row>;
2✔
508
                        }
509
                        return null;
60✔
510
                    };
511

512
                    renderPreviewPanel = () => {
18✔
513
                        return this.renderItems("preview-panel", this.props.previewOptions);
2✔
514
                    };
515

516
                    renderBody = () => {
18✔
517
                        if (this.props.pdfUrl && this.props.usePreview) {
64✔
518
                            return this.renderPreviewPanel();
2✔
519
                        }
520
                        return this.renderPrintPanel();
62✔
521
                    };
522

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

565
                    isBackgroundIgnored = (layers, projection) => {
18✔
566
                        const background = head((layers || this.props.layers)
132!
567
                            .filter(layer => layer.group === "background" && layer.visibility && this.isAllowed(layer, projection)));
73!
568
                        return !background;
132✔
569
                    };
570
                    filterLayers = (layers, zoom, projection) => {
18✔
571
                        const resolution = this.getPreviewResolution(zoom, projection);
70✔
572

573
                        const filtered = layers.filter((layer) =>
70✔
574
                            layer.visibility &&
40✔
575
                            isInsideResolutionsLimits(layer, resolution) &&
576
                            this.isAllowed(layer, projection)
577
                        );
578
                        if (this.isBackgroundIgnored(layers, projection) && this.props.defaultBackground && this.props.printSpec.defaultBackground) {
70✔
579
                            const defaultBackground = this.getAlternativeBackground(layers, this.props.defaultBackground);
5✔
580
                            if (defaultBackground) {
5!
581
                                return [{
×
582
                                    ...defaultBackground,
583
                                    visibility: true
584
                                }, ...filtered];
585
                            }
586
                            return filtered;
5✔
587
                        }
588
                        return filtered;
65✔
589
                    };
590
                    getRatio = () => {
18✔
591
                        let mapPrintLayout = this.getLayout();
366✔
592
                        if (this.props?.mapWidth && mapPrintLayout) {
366!
593
                            return getResolutionMultiplier(mapPrintLayout?.map?.width || 0, this?.props?.mapWidth || 0, this.props.printRatio);
366!
594
                        }
NEW
595
                        return 1;
×
596
                    };
597
                    configurePrintMap = (props) => {
18✔
598
                        const {
599
                            map: newMap,
600
                            capabilities,
601
                            configurePrintMap: configurePrintMapProp,
602
                            useFixedScales,
603
                            currentLocale,
604
                            layers,
605
                            printMap,
606
                            printSpec,
607
                            disableScaleLocking
608
                        } = props || this.props;
19✔
609
                        if (newMap && newMap.bbox && capabilities) {
19!
610
                            const selectedPrintProjection = (printSpec && printSpec?.params?.projection) || (printSpec && printSpec?.projection) || (printMap && printMap.projection) || 'EPSG:3857';
19!
611
                            const printSrs = normalizeSRS(selectedPrintProjection);
19✔
612
                            const mapProjection = newMap.projection;
19✔
613
                            const mapSrs = normalizeSRS(mapProjection);
19✔
614
                            const zoom = reprojectZoom(newMap.zoom, mapSrs, printSrs);
19✔
615
                            const scales = getPrintScales(capabilities);
19✔
616
                            const printMapScales = getScales(printSrs);
19✔
617
                            const scaleZoom = getNearestZoom(zoom, scales, printMapScales);
19✔
618
                            if (useFixedScales && !disableScaleLocking) {
19✔
619
                                const scale = scales[scaleZoom];
4✔
620
                                configurePrintMapProp(newMap.center, zoom, scaleZoom, scale,
4✔
621
                                    layers, newMap.projection, currentLocale, useFixedScales);
622
                            } else {
623
                                const scale = printMapScales[zoom];
15✔
624
                                let resolutions = getResolutions(printSrs).map((resolution) => resolution * this.getRatio());
366✔
625
                                const reqScaleZoom = disableScaleLocking ? zoom : scaleZoom;
15✔
626
                                configurePrintMapProp(newMap.center, zoom, reqScaleZoom, scale,
15✔
627
                                    layers, newMap.projection, currentLocale, useFixedScales, {
628
                                        disableScaleLocking,
629
                                        mapResolution: resolutions[zoom]
630
                                    });
631
                            }
632
                        }
633
                    };
634

635
                    print = () => {
18✔
636
                        this.props.setPage(0);
8✔
637
                        this.props.onBeforePrint();
8✔
638
                        this.props.printingService.print({
8✔
639
                            excludeLayersFromLegend: this.props.excludeLayersFromLegend,
640
                            mergeableParams: this.props.mergeableParams,
641
                            layers: this.getMapConfiguration()?.layers,
642
                            scales: this.props.useFixedScales && !this.props.disableScaleLocking ? getPrintScales(this.props.capabilities) : undefined,
18✔
643
                            bbox: this.props.map?.bbox
644
                        })
645
                            .then((spec) =>
646
                                this.props.onPrint(this.props.capabilities.createURL, { ...spec, ...this.props.overrideOptions })
6✔
647
                            )
648
                            .catch(e => {
649
                                this.props.printError("Error in printing:" + e.message);
×
650
                            });
651
                    };
652
                }
653

654
                const selector = createSelector([
18✔
655
                    (state) => state.controls.print && state.controls.print.enabled || state.controls.toolbar && state.controls.toolbar.active === 'print',
64!
656
                    (state) => state.print && state.print.capabilities,
64✔
657
                    printSpecificationSelector,
658
                    (state) => state.print && state.print.pdfUrl,
64✔
659
                    (state) => state.print && state.print.error,
64✔
660
                    mapSelector,
661
                    layersSelector,
662
                    additionalLayersSelector,
663
                    scalesSelector,
664
                    (state) => state.browser && (!state.browser.ie || state.browser.ie11),
64!
665
                    currentLocaleSelector,
666
                    mapTypeSelector,
667
                    (state) => state.print.map,
64✔
668
                    rawGroupsSelector
669
                ], (open, capabilities, printSpec, pdfUrl, error, map, layers, additionalLayers, scales, usePreview, currentLocale, mapType, printMap, groups) => ({
64✔
670
                    open,
671
                    capabilities,
672
                    printSpec,
673
                    pdfUrl,
674
                    error,
675
                    map,
676
                    layers: [
677
                        ...getDerivedLayersVisibility(layers, groups).filter(filterLayer),
678
                        ...(printSpec?.additionalLayers ? additionalLayers.map(l => l.options).filter(
×
679
                            l => {
680
                                const isVector = l.type === 'vector';
×
681
                                const hasFeatures = Array.isArray(l.features) && l.features.length > 0;
×
682
                                return !l.loadingError && (!isVector || (isVector && hasFeatures));
×
683
                            }
684
                        ) : [])
685
                    ],
686
                    scales,
687
                    usePreview,
688
                    currentLocale,
689
                    mapType,
690
                    printMap
691
                }));
692

693
                const PrintPlugin = connect(selector, {
18✔
694
                    toggleControl: toggleControl.bind(null, 'print', null),
695
                    onPrint: printSubmit,
696
                    printError: printError,
697
                    onBeforePrint: printSubmitting,
698
                    setPage: setControlProperty.bind(null, 'print', 'currentPage'),
699
                    configurePrintMap,
700
                    addPrintParameter
701
                })(Print);
702
                resolve(PrintPlugin);
18✔
703
            });
704
        },
705
        enabler: (state) => state.print && state.print.enabled || state.toolbar && state.toolbar.active === 'print'
×
706
    },
707
    {
708
        disablePluginIf: "{state('mapType') === 'cesium' || !state('printEnabled')}",
709
        Toolbar: {
710
            name: 'print',
711
            position: 7,
712
            help: <Message msgId="helptexts.print"/>,
713
            tooltip: "printbutton",
714
            icon: <Glyphicon glyph="print"/>,
715
            exclusive: true,
716
            panel: true,
717
            priority: 1
718
        },
719
        BurgerMenu: {
720
            name: 'print',
721
            position: 2,
722
            tooltip: "printToolTip",
723
            text: <Message msgId="printbutton"/>,
724
            icon: <Glyphicon glyph="print"/>,
725
            action: toggleControl.bind(null, 'print', null),
726
            priority: 3,
727
            doNotHide: true
728
        },
729
        SidebarMenu: {
730
            name: "print",
731
            position: 3,
732
            tooltip: "printbutton",
733
            text: <Message msgId="printbutton"/>,
734
            icon: <Glyphicon glyph="print"/>,
735
            action: toggleControl.bind(null, 'print', null),
736
            doNotHide: true,
737
            toggle: true,
738
            priority: 2
739
        }
740
    }),
741
    reducers: {print: printReducers},
742
    epics: {...printEpics}
743
};
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