From 5504abfddf1183d6f22844e95e7b35cd565aac26 Mon Sep 17 00:00:00 2001 From: Divyansh Yadav Date: Sat, 28 Nov 2026 14:09:08 +0530 Subject: [PATCH] fix(dashboard): export PDF when an external map is on the dashboard --- .../src/util/layerUtil.tsx | 11 ++++ .../test/util/layerUtil.test.ts | 30 +++++++++++ .../src/utils/downloadAsPdf.test.ts | 54 +++++++++++++++++++ superset-frontend/src/utils/downloadAsPdf.ts | 39 +++++++++++++- 4 files changed, 133 insertions(+), 1 deletion(-) diff --git a/superset-frontend/plugins/plugin-chart-cartodiagram/src/util/layerUtil.tsx b/superset-frontend/plugins/plugin-chart-cartodiagram/src/util/layerUtil.tsx index 25084f69223d..bff95b9bdfd8 100644 --- a/superset-frontend/plugins/plugin-chart-cartodiagram/src/util/layerUtil.tsx +++ b/superset-frontend/plugins/plugin-chart-cartodiagram/src/util/layerUtil.tsx @@ -54,6 +54,15 @@ export const escapeAttribution = (attribution?: string): string | undefined => .replace(/"/g, '"') .replace(/'/g, '''); +/** + * The crossOrigin setting for tile images. + * + * Tiles usually come from an external server. Without a CORS request they + * taint the map canvas, and exporting a dashboard as PDF fails because the + * canvas can no longer be read. + */ +const TILE_CROSS_ORIGIN = 'anonymous'; + /** * Create a WMS layer. * @@ -71,6 +80,7 @@ export const createWmsLayer = (wmsLayerConf: WmsLayerConf) => { VERSION: version, }, attributions: escapeAttribution(attribution), + crossOrigin: TILE_CROSS_ORIGIN, }), }); }; @@ -88,6 +98,7 @@ export const createXyzLayer = (xyzLayerConf: XyzLayerConf) => { source: new XyzSource({ url, attributions: escapeAttribution(attribution), + crossOrigin: TILE_CROSS_ORIGIN, }), }); }; diff --git a/superset-frontend/plugins/plugin-chart-cartodiagram/test/util/layerUtil.test.ts b/superset-frontend/plugins/plugin-chart-cartodiagram/test/util/layerUtil.test.ts index 033cfbe059dd..70985652a5f8 100644 --- a/superset-frontend/plugins/plugin-chart-cartodiagram/test/util/layerUtil.test.ts +++ b/superset-frontend/plugins/plugin-chart-cartodiagram/test/util/layerUtil.test.ts @@ -17,6 +17,8 @@ * under the License. */ +import ImageTile from 'ol/ImageTile'; +import { get as getProjection } from 'ol/proj'; import { WfsLayerConf, WmsLayerConf, XyzLayerConf } from '../../src/types'; import { createLayer, @@ -60,9 +62,37 @@ describe('layerUtil', () => { '(c) OSM <img src=x onerror=alert(1)>', ]); }); + + test('requests tiles with CORS so the map canvas stays exportable', () => { + const wmsLayerConf: WmsLayerConf = { + title: 'wms', + type: 'WMS', + url: 'https://ows-demo.terrestris.de/geoserver/osm/wms', + version: '1.3.0', + layersParam: 'osm:osm-fuel', + }; + const layer = createWmsLayer(wmsLayerConf); + const tile = layer + .getSource()! + .getTile(0, 0, 0, 1, getProjection('EPSG:3857')!) as ImageTile; + expect(tile.getCrossOrigin()).toEqual('anonymous'); + }); }); describe('createXyzLayer', () => { + test('requests tiles with CORS so the map canvas stays exportable', () => { + const xyzLayerConf: XyzLayerConf = { + title: 'osm', + type: 'XYZ', + url: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png', + }; + const layer = createXyzLayer(xyzLayerConf); + const tile = layer + .getSource()! + .getTile(0, 0, 0, 1, getProjection('EPSG:3857')!) as ImageTile; + expect(tile.getCrossOrigin()).toEqual('anonymous'); + }); + test('escapes HTML in the layer attribution', () => { const xyzLayerConf: XyzLayerConf = { title: 'osm', diff --git a/superset-frontend/src/utils/downloadAsPdf.test.ts b/superset-frontend/src/utils/downloadAsPdf.test.ts index 21d5eda7a116..561f6b84c548 100644 --- a/superset-frontend/src/utils/downloadAsPdf.test.ts +++ b/superset-frontend/src/utils/downloadAsPdf.test.ts @@ -103,6 +103,60 @@ test('warns the user via the bound toast callback when PDF generation fails', as ); }); +const createCanvases = () => { + const element = document.createElement('div'); + const taintedCanvas = document.createElement('canvas'); + const cleanCanvas = document.createElement('canvas'); + jest.spyOn(taintedCanvas, 'toDataURL').mockImplementation(() => { + throw new DOMException('Tainted canvases may not be exported.'); + }); + jest.spyOn(cleanCanvas, 'toDataURL').mockReturnValue('data:,'); + element.append(taintedCanvas, cleanCanvas); + return { element, taintedCanvas, cleanCanvas }; +}; + +test('excludes tainted canvases from the PDF instead of failing the export', async () => { + const { element, taintedCanvas, cleanCanvas } = createCanvases(); + jest.spyOn(document, 'querySelector').mockReturnValue(element); + const domToPdf = jest.requireMock('dom-to-pdf').default as jest.Mock; + let classesDuringExport: { tainted: string; clean: string } | undefined; + domToPdf.mockImplementation(() => { + classesDuringExport = { + tainted: taintedCanvas.className, + clean: cleanCanvas.className, + }; + return Promise.resolve(); + }); + + await downloadAsPdf( + '.some-selector', + 'test-file', + true, + )({} as SyntheticEvent); + + const { excludeClassNames } = domToPdf.mock.calls[0][1]; + expect(excludeClassNames).toContain('header-controls'); + expect(excludeClassNames).toContain(classesDuringExport?.tainted); + expect(classesDuringExport?.tainted).not.toBe(''); + expect(classesDuringExport?.clean).toBe(''); +}); + +test('removes the tainted canvas marker once the export settles', async () => { + const { element, taintedCanvas } = createCanvases(); + jest.spyOn(document, 'querySelector').mockReturnValue(element); + const domToPdf = jest.requireMock('dom-to-pdf').default as jest.Mock; + domToPdf.mockRejectedValue(new Error('boom')); + + await downloadAsPdf( + '.some-selector', + 'test-file', + true, + )({} as SyntheticEvent); + + expect(domToPdf).toHaveBeenCalled(); + expect(taintedCanvas.className).toBe(''); +}); + test('forwards both bound toast callbacks to forceLoadAllCharts', async () => { const element = document.createElement('div'); jest.spyOn(document, 'querySelector').mockReturnValue(element); diff --git a/superset-frontend/src/utils/downloadAsPdf.ts b/superset-frontend/src/utils/downloadAsPdf.ts index 449ec8266d30..df61baec9419 100644 --- a/superset-frontend/src/utils/downloadAsPdf.ts +++ b/superset-frontend/src/utils/downloadAsPdf.ts @@ -30,6 +30,38 @@ const PDF_DOWNLOAD_FAILED_MESSAGE = t( 'PDF download failed, please refresh and try again.', ); +const UNEXPORTABLE_CANVAS_CLASS = 'pdf-export-unexportable-canvas'; + +/** + * check whether a canvas can be read back, which fails with a SecurityError + * once cross-origin content (e.g. external map tiles) has been drawn into it + * + * @param canvas canvas element to check + */ +const isCanvasExportable = (canvas: HTMLCanvasElement) => { + try { + canvas.toDataURL(); + return true; + } catch { + return false; + } +}; + +/** + * mark tainted canvases so dom-to-pdf leaves them out instead of failing the + * whole export when it reads them + * + * @param element element that is about to be printed + * @returns the canvases that were marked + */ +const markUnexportableCanvases = (element: Element) => { + const canvases = Array.from(element.querySelectorAll('canvas')).filter( + canvas => !isCanvasExportable(canvas), + ); + canvases.forEach(canvas => canvas.classList.add(UNEXPORTABLE_CANVAS_CLASS)); + return canvases; +}; + /** * generate a consistent file stem from a description and date * @@ -79,13 +111,15 @@ export default function downloadAsPdf( addInfoToast, ); + const unexportableCanvases = markUnexportableCanvases(elementToPrint); + const options = { margin: 10, compression: pdfCompressionLevel, filename: `${generateFileStem(description)}.pdf`, image: { type: 'jpeg', quality: 1 }, html2canvas: { scale: 2 }, - excludeClassNames: ['header-controls'], + excludeClassNames: ['header-controls', UNEXPORTABLE_CANVAS_CLASS], }; return domToPdf(elementToPrint, options) .then(() => { @@ -96,6 +130,9 @@ export default function downloadAsPdf( addWarningToast?.(PDF_DOWNLOAD_FAILED_MESSAGE); }) .finally(() => { + unexportableCanvases.forEach(canvas => + canvas.classList.remove(UNEXPORTABLE_CANVAS_CLASS), + ); if (didForceLoad) { restoreVirtualization(); }