OfflineExporting.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  1. /* *
  2. *
  3. * Client side exporting module
  4. *
  5. * (c) 2015 Torstein Honsi / Oystein Moseng
  6. *
  7. * License: www.highcharts.com/license
  8. *
  9. * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
  10. *
  11. * */
  12. import Chart from '../Core/Chart/Chart.js';
  13. import H from '../Core/Globals.js';
  14. var win = H.win, doc = H.doc;
  15. import '../Core/Options.js';
  16. import SVGRenderer from '../Core/Renderer/SVG/SVGRenderer.js';
  17. import U from '../Core/Utilities.js';
  18. var addEvent = U.addEvent, error = U.error, extend = U.extend, getOptions = U.getOptions, merge = U.merge;
  19. import DownloadURL from '../Extensions/DownloadURL.js';
  20. var downloadURL = DownloadURL.downloadURL;
  21. var domurl = win.URL || win.webkitURL || win, nav = win.navigator, isMSBrowser = /Edge\/|Trident\/|MSIE /.test(nav.userAgent),
  22. // Milliseconds to defer image load event handlers to offset IE bug
  23. loadEventDeferDelay = isMSBrowser ? 150 : 0;
  24. // Dummy object so we can reuse our canvas-tools.js without errors
  25. H.CanVGRenderer = {};
  26. /* eslint-disable valid-jsdoc */
  27. /**
  28. * Downloads a script and executes a callback when done.
  29. *
  30. * @private
  31. * @function getScript
  32. * @param {string} scriptLocation
  33. * @param {Function} callback
  34. * @return {void}
  35. */
  36. function getScript(scriptLocation, callback) {
  37. var head = doc.getElementsByTagName('head')[0], script = doc.createElement('script');
  38. script.type = 'text/javascript';
  39. script.src = scriptLocation;
  40. script.onload = callback;
  41. script.onerror = function () {
  42. error('Error loading script ' + scriptLocation);
  43. };
  44. head.appendChild(script);
  45. }
  46. /**
  47. * Get blob URL from SVG code. Falls back to normal data URI.
  48. *
  49. * @private
  50. * @function Highcharts.svgToDataURL
  51. * @param {string} svg
  52. * @return {string}
  53. */
  54. function svgToDataUrl(svg) {
  55. // Webkit and not chrome
  56. var webKit = (nav.userAgent.indexOf('WebKit') > -1 &&
  57. nav.userAgent.indexOf('Chrome') < 0);
  58. try {
  59. // Safari requires data URI since it doesn't allow navigation to blob
  60. // URLs. Firefox has an issue with Blobs and internal references,
  61. // leading to gradients not working using Blobs (#4550)
  62. if (!webKit && nav.userAgent.toLowerCase().indexOf('firefox') < 0) {
  63. return domurl.createObjectURL(new win.Blob([svg], {
  64. type: 'image/svg+xml;charset-utf-16'
  65. }));
  66. }
  67. }
  68. catch (e) {
  69. // Ignore
  70. }
  71. return 'data:image/svg+xml;charset=UTF-8,' + encodeURIComponent(svg);
  72. }
  73. /**
  74. * Get data:URL from image URL. Pass in callbacks to handle results.
  75. *
  76. * @private
  77. * @function Highcharts.imageToDataUrl
  78. *
  79. * @param {string} imageURL
  80. *
  81. * @param {string} imageType
  82. *
  83. * @param {*} callbackArgs
  84. * callbackArgs is used only by callbacks.
  85. *
  86. * @param {number} scale
  87. *
  88. * @param {Function} successCallback
  89. * Receives four arguments: imageURL, imageType, callbackArgs, and scale.
  90. *
  91. * @param {Function} taintedCallback
  92. * Receives four arguments: imageURL, imageType, callbackArgs, and scale.
  93. *
  94. * @param {Function} noCanvasSupportCallback
  95. * Receives four arguments: imageURL, imageType, callbackArgs, and scale.
  96. *
  97. * @param {Function} failedLoadCallback
  98. * Receives four arguments: imageURL, imageType, callbackArgs, and scale.
  99. *
  100. * @param {Function} [finallyCallback]
  101. * finallyCallback is always called at the end of the process. All
  102. * callbacks receive four arguments: imageURL, imageType, callbackArgs,
  103. * and scale.
  104. *
  105. * @return {void}
  106. */
  107. function imageToDataUrl(imageURL, imageType, callbackArgs, scale, successCallback, taintedCallback, noCanvasSupportCallback, failedLoadCallback, finallyCallback) {
  108. var img = new win.Image(), taintedHandler, loadHandler = function () {
  109. setTimeout(function () {
  110. var canvas = doc.createElement('canvas'), ctx = canvas.getContext && canvas.getContext('2d'), dataURL;
  111. try {
  112. if (!ctx) {
  113. noCanvasSupportCallback(imageURL, imageType, callbackArgs, scale);
  114. }
  115. else {
  116. canvas.height = img.height * scale;
  117. canvas.width = img.width * scale;
  118. ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
  119. // Now we try to get the contents of the canvas.
  120. try {
  121. dataURL = canvas.toDataURL(imageType);
  122. successCallback(dataURL, imageType, callbackArgs, scale);
  123. }
  124. catch (e) {
  125. taintedHandler(imageURL, imageType, callbackArgs, scale);
  126. }
  127. }
  128. }
  129. finally {
  130. if (finallyCallback) {
  131. finallyCallback(imageURL, imageType, callbackArgs, scale);
  132. }
  133. }
  134. // IE bug where image is not always ready despite calling load
  135. // event.
  136. }, loadEventDeferDelay);
  137. },
  138. // Image load failed (e.g. invalid URL)
  139. errorHandler = function () {
  140. failedLoadCallback(imageURL, imageType, callbackArgs, scale);
  141. if (finallyCallback) {
  142. finallyCallback(imageURL, imageType, callbackArgs, scale);
  143. }
  144. };
  145. // This is called on load if the image drawing to canvas failed with a
  146. // security error. We retry the drawing with crossOrigin set to Anonymous.
  147. taintedHandler = function () {
  148. img = new win.Image();
  149. taintedHandler = taintedCallback;
  150. // Must be set prior to loading image source
  151. img.crossOrigin = 'Anonymous';
  152. img.onload = loadHandler;
  153. img.onerror = errorHandler;
  154. img.src = imageURL;
  155. };
  156. img.onload = loadHandler;
  157. img.onerror = errorHandler;
  158. img.src = imageURL;
  159. }
  160. /* eslint-enable valid-jsdoc */
  161. /**
  162. * Get data URL to an image of an SVG and call download on it options object:
  163. *
  164. * - **filename:** Name of resulting downloaded file without extension. Default
  165. * is `chart`.
  166. *
  167. * - **type:** File type of resulting download. Default is `image/png`.
  168. *
  169. * - **scale:** Scaling factor of downloaded image compared to source. Default
  170. * is `1`.
  171. *
  172. * - **libURL:** URL pointing to location of dependency scripts to download on
  173. * demand. Default is the exporting.libURL option of the global Highcharts
  174. * options pointing to our server.
  175. *
  176. * @function Highcharts.downloadSVGLocal
  177. *
  178. * @param {string} svg
  179. * The generated SVG
  180. *
  181. * @param {Highcharts.ExportingOptions} options
  182. * The exporting options
  183. *
  184. * @param {Function} failCallback
  185. * The callback function in case of errors
  186. *
  187. * @param {Function} [successCallback]
  188. * The callback function in case of success
  189. *
  190. * @return {void}
  191. */
  192. function downloadSVGLocal(svg, options, failCallback, successCallback) {
  193. var svgurl, blob, objectURLRevoke = true, finallyHandler, libURL = (options.libURL || getOptions().exporting.libURL), dummySVGContainer = doc.createElement('div'), imageType = options.type || 'image/png', filename = ((options.filename || 'chart') +
  194. '.' +
  195. (imageType === 'image/svg+xml' ? 'svg' : imageType.split('/')[1])), scale = options.scale || 1;
  196. // Allow libURL to end with or without fordward slash
  197. libURL = libURL.slice(-1) !== '/' ? libURL + '/' : libURL;
  198. /* eslint-disable valid-jsdoc */
  199. /**
  200. * @private
  201. */
  202. function svgToPdf(svgElement, margin) {
  203. var width = svgElement.width.baseVal.value + 2 * margin, height = svgElement.height.baseVal.value + 2 * margin, pdf = new win.jsPDF(// eslint-disable-line new-cap
  204. height > width ? 'p' : 'l', // setting orientation to portrait if height exceeds width
  205. 'pt', [width, height]);
  206. // Workaround for #7090, hidden elements were drawn anyway. It comes
  207. // down to https://github.com/yWorks/svg2pdf.js/issues/28. Check this
  208. // later.
  209. [].forEach.call(svgElement.querySelectorAll('*[visibility="hidden"]'), function (node) {
  210. node.parentNode.removeChild(node);
  211. });
  212. win.svg2pdf(svgElement, pdf, { removeInvalid: true });
  213. return pdf.output('datauristring');
  214. }
  215. /**
  216. * @private
  217. * @return {void}
  218. */
  219. function downloadPDF() {
  220. dummySVGContainer.innerHTML = svg;
  221. var textElements = dummySVGContainer.getElementsByTagName('text'), titleElements, svgData,
  222. // Copy style property to element from parents if it's not there.
  223. // Searches up hierarchy until it finds prop, or hits the chart
  224. // container.
  225. setStylePropertyFromParents = function (el, propName) {
  226. var curParent = el;
  227. while (curParent && curParent !== dummySVGContainer) {
  228. if (curParent.style[propName]) {
  229. el.style[propName] =
  230. curParent.style[propName];
  231. break;
  232. }
  233. curParent = curParent.parentNode;
  234. }
  235. };
  236. // Workaround for the text styling. Making sure it does pick up settings
  237. // for parent elements.
  238. [].forEach.call(textElements, function (el) {
  239. // Workaround for the text styling. making sure it does pick up the
  240. // root element
  241. ['font-family', 'font-size'].forEach(function (property) {
  242. setStylePropertyFromParents(el, property);
  243. });
  244. el.style['font-family'] = (el.style['font-family'] &&
  245. el.style['font-family'].split(' ').splice(-1));
  246. // Workaround for plotband with width, removing title from text
  247. // nodes
  248. titleElements = el.getElementsByTagName('title');
  249. [].forEach.call(titleElements, function (titleElement) {
  250. el.removeChild(titleElement);
  251. });
  252. });
  253. svgData = svgToPdf(dummySVGContainer.firstChild, 0);
  254. try {
  255. downloadURL(svgData, filename);
  256. if (successCallback) {
  257. successCallback();
  258. }
  259. }
  260. catch (e) {
  261. failCallback(e);
  262. }
  263. }
  264. /* eslint-enable valid-jsdoc */
  265. // Initiate download depending on file type
  266. if (imageType === 'image/svg+xml') {
  267. // SVG download. In this case, we want to use Microsoft specific Blob if
  268. // available
  269. try {
  270. if (typeof nav.msSaveOrOpenBlob !== 'undefined') {
  271. blob = new MSBlobBuilder();
  272. blob.append(svg);
  273. svgurl = blob.getBlob('image/svg+xml');
  274. }
  275. else {
  276. svgurl = svgToDataUrl(svg);
  277. }
  278. downloadURL(svgurl, filename);
  279. if (successCallback) {
  280. successCallback();
  281. }
  282. }
  283. catch (e) {
  284. failCallback(e);
  285. }
  286. }
  287. else if (imageType === 'application/pdf') {
  288. if (win.jsPDF && win.svg2pdf) {
  289. downloadPDF();
  290. }
  291. else {
  292. // Must load pdf libraries first. // Don't destroy the object URL
  293. // yet since we are doing things asynchronously. A cleaner solution
  294. // would be nice, but this will do for now.
  295. objectURLRevoke = true;
  296. getScript(libURL + 'jspdf.js', function () {
  297. getScript(libURL + 'svg2pdf.js', function () {
  298. downloadPDF();
  299. });
  300. });
  301. }
  302. }
  303. else {
  304. // PNG/JPEG download - create bitmap from SVG
  305. svgurl = svgToDataUrl(svg);
  306. finallyHandler = function () {
  307. try {
  308. domurl.revokeObjectURL(svgurl);
  309. }
  310. catch (e) {
  311. // Ignore
  312. }
  313. };
  314. // First, try to get PNG by rendering on canvas
  315. imageToDataUrl(svgurl, imageType, {}, scale, function (imageURL) {
  316. // Success
  317. try {
  318. downloadURL(imageURL, filename);
  319. if (successCallback) {
  320. successCallback();
  321. }
  322. }
  323. catch (e) {
  324. failCallback(e);
  325. }
  326. }, function () {
  327. // Failed due to tainted canvas
  328. // Create new and untainted canvas
  329. var canvas = doc.createElement('canvas'), ctx = canvas.getContext('2d'), imageWidth = svg.match(/^<svg[^>]*width\s*=\s*\"?(\d+)\"?[^>]*>/)[1] * scale, imageHeight = svg.match(/^<svg[^>]*height\s*=\s*\"?(\d+)\"?[^>]*>/)[1] * scale, downloadWithCanVG = function () {
  330. ctx.drawSvg(svg, 0, 0, imageWidth, imageHeight);
  331. try {
  332. downloadURL(nav.msSaveOrOpenBlob ?
  333. canvas.msToBlob() :
  334. canvas.toDataURL(imageType), filename);
  335. if (successCallback) {
  336. successCallback();
  337. }
  338. }
  339. catch (e) {
  340. failCallback(e);
  341. }
  342. finally {
  343. finallyHandler();
  344. }
  345. };
  346. canvas.width = imageWidth;
  347. canvas.height = imageHeight;
  348. if (win.canvg) {
  349. // Use preloaded canvg
  350. downloadWithCanVG();
  351. }
  352. else {
  353. // Must load canVG first. // Don't destroy the object URL
  354. // yet since we are doing things asynchronously. A cleaner
  355. // solution would be nice, but this will do for now.
  356. objectURLRevoke = true;
  357. // Get RGBColor.js first, then canvg
  358. getScript(libURL + 'rgbcolor.js', function () {
  359. getScript(libURL + 'canvg.js', function () {
  360. downloadWithCanVG();
  361. });
  362. });
  363. }
  364. },
  365. // No canvas support
  366. failCallback,
  367. // Failed to load image
  368. failCallback,
  369. // Finally
  370. function () {
  371. if (objectURLRevoke) {
  372. finallyHandler();
  373. }
  374. });
  375. }
  376. }
  377. /* eslint-disable valid-jsdoc */
  378. /**
  379. * Get SVG of chart prepared for client side export. This converts embedded
  380. * images in the SVG to data URIs. It requires the regular exporting module. The
  381. * options and chartOptions arguments are passed to the getSVGForExport
  382. * function.
  383. *
  384. * @private
  385. * @function Highcharts.Chart#getSVGForLocalExport
  386. * @param {Highcharts.ExportingOptions} options
  387. * @param {Highcharts.Options} chartOptions
  388. * @param {Function} failCallback
  389. * @param {Function} successCallback
  390. * @return {void}
  391. */
  392. Chart.prototype.getSVGForLocalExport = function (options, chartOptions, failCallback, successCallback) {
  393. var chart = this, images, imagesEmbedded = 0, chartCopyContainer, chartCopyOptions, el, i, l, href,
  394. // After grabbing the SVG of the chart's copy container we need to do
  395. // sanitation on the SVG
  396. sanitize = function (svg) {
  397. return chart.sanitizeSVG(svg, chartCopyOptions);
  398. },
  399. // When done with last image we have our SVG
  400. checkDone = function () {
  401. if (imagesEmbedded === images.length) {
  402. successCallback(sanitize(chartCopyContainer.innerHTML));
  403. }
  404. },
  405. // Success handler, we converted image to base64!
  406. embeddedSuccess = function (imageURL, imageType, callbackArgs) {
  407. ++imagesEmbedded;
  408. // Change image href in chart copy
  409. callbackArgs.imageElement.setAttributeNS('http://www.w3.org/1999/xlink', 'href', imageURL);
  410. checkDone();
  411. };
  412. // Hook into getSVG to get a copy of the chart copy's container (#8273)
  413. chart.unbindGetSVG = addEvent(chart, 'getSVG', function (e) {
  414. chartCopyOptions = e.chartCopy.options;
  415. chartCopyContainer = e.chartCopy.container.cloneNode(true);
  416. });
  417. // Trigger hook to get chart copy
  418. chart.getSVGForExport(options, chartOptions);
  419. images = chartCopyContainer.getElementsByTagName('image');
  420. try {
  421. // If there are no images to embed, the SVG is okay now.
  422. if (!images.length) {
  423. // Use SVG of chart copy
  424. successCallback(sanitize(chartCopyContainer.innerHTML));
  425. return;
  426. }
  427. // Go through the images we want to embed
  428. for (i = 0, l = images.length; i < l; ++i) {
  429. el = images[i];
  430. href = el.getAttributeNS('http://www.w3.org/1999/xlink', 'href');
  431. if (href) {
  432. imageToDataUrl(href, 'image/png', { imageElement: el }, options.scale, embeddedSuccess,
  433. // Tainted canvas
  434. failCallback,
  435. // No canvas support
  436. failCallback,
  437. // Failed to load source
  438. failCallback);
  439. // Hidden, boosted series have blank href (#10243)
  440. }
  441. else {
  442. ++imagesEmbedded;
  443. el.parentNode.removeChild(el);
  444. checkDone();
  445. }
  446. }
  447. }
  448. catch (e) {
  449. failCallback(e);
  450. }
  451. // Clean up
  452. chart.unbindGetSVG();
  453. };
  454. /* eslint-enable valid-jsdoc */
  455. /**
  456. * Exporting and offline-exporting modules required. Export a chart to an image
  457. * locally in the user's browser.
  458. *
  459. * @function Highcharts.Chart#exportChartLocal
  460. *
  461. * @param {Highcharts.ExportingOptions} [exportingOptions]
  462. * Exporting options, the same as in
  463. * {@link Highcharts.Chart#exportChart}.
  464. *
  465. * @param {Highcharts.Options} [chartOptions]
  466. * Additional chart options for the exported chart. For example a
  467. * different background color can be added here, or `dataLabels`
  468. * for export only.
  469. *
  470. * @return {void}
  471. *
  472. * @requires modules/exporting
  473. */
  474. Chart.prototype.exportChartLocal = function (exportingOptions, chartOptions) {
  475. var chart = this, options = merge(chart.options.exporting, exportingOptions), fallbackToExportServer = function (err) {
  476. if (options.fallbackToExportServer === false) {
  477. if (options.error) {
  478. options.error(options, err);
  479. }
  480. else {
  481. error(28, true); // Fallback disabled
  482. }
  483. }
  484. else {
  485. chart.exportChart(options);
  486. }
  487. }, svgSuccess = function (svg) {
  488. // If SVG contains foreignObjects all exports except SVG will fail,
  489. // as both CanVG and svg2pdf choke on this. Gracefully fall back.
  490. if (svg.indexOf('<foreignObject') > -1 &&
  491. options.type !== 'image/svg+xml') {
  492. fallbackToExportServer('Image type not supported' +
  493. 'for charts with embedded HTML');
  494. }
  495. else {
  496. downloadSVGLocal(svg, extend({ filename: chart.getFilename() }, options), fallbackToExportServer);
  497. }
  498. },
  499. // Return true if the SVG contains images with external data. With the
  500. // boost module there are `image` elements with encoded PNGs, these are
  501. // supported by svg2pdf and should pass (#10243).
  502. hasExternalImages = function () {
  503. return [].some.call(chart.container.getElementsByTagName('image'), function (image) {
  504. var href = image.getAttribute('href');
  505. return href !== '' && href.indexOf('data:') !== 0;
  506. });
  507. };
  508. // If we are on IE and in styled mode, add a whitelist to the renderer for
  509. // inline styles that we want to pass through. There are so many styles by
  510. // default in IE that we don't want to blacklist them all.
  511. if (isMSBrowser && chart.styledMode) {
  512. SVGRenderer.prototype.inlineWhitelist = [
  513. /^blockSize/,
  514. /^border/,
  515. /^caretColor/,
  516. /^color/,
  517. /^columnRule/,
  518. /^columnRuleColor/,
  519. /^cssFloat/,
  520. /^cursor/,
  521. /^fill$/,
  522. /^fillOpacity/,
  523. /^font/,
  524. /^inlineSize/,
  525. /^length/,
  526. /^lineHeight/,
  527. /^opacity/,
  528. /^outline/,
  529. /^parentRule/,
  530. /^rx$/,
  531. /^ry$/,
  532. /^stroke/,
  533. /^textAlign/,
  534. /^textAnchor/,
  535. /^textDecoration/,
  536. /^transform/,
  537. /^vectorEffect/,
  538. /^visibility/,
  539. /^x$/,
  540. /^y$/
  541. ];
  542. }
  543. // Always fall back on:
  544. // - MS browsers: Embedded images JPEG/PNG, or any PDF
  545. // - Embedded images and PDF
  546. if ((isMSBrowser &&
  547. (options.type === 'application/pdf' ||
  548. chart.container.getElementsByTagName('image').length &&
  549. options.type !== 'image/svg+xml')) || (options.type === 'application/pdf' &&
  550. hasExternalImages())) {
  551. fallbackToExportServer('Image type not supported for this chart/browser.');
  552. return;
  553. }
  554. chart.getSVGForLocalExport(options, chartOptions, fallbackToExportServer, svgSuccess);
  555. };
  556. // Extend the default options to use the local exporter logic
  557. merge(true, getOptions().exporting, {
  558. libURL: 'https://code.highcharts.com/8.2.2/lib/',
  559. // When offline-exporting is loaded, redefine the menu item definitions
  560. // related to download.
  561. menuItemDefinitions: {
  562. downloadPNG: {
  563. textKey: 'downloadPNG',
  564. onclick: function () {
  565. this.exportChartLocal();
  566. }
  567. },
  568. downloadJPEG: {
  569. textKey: 'downloadJPEG',
  570. onclick: function () {
  571. this.exportChartLocal({
  572. type: 'image/jpeg'
  573. });
  574. }
  575. },
  576. downloadSVG: {
  577. textKey: 'downloadSVG',
  578. onclick: function () {
  579. this.exportChartLocal({
  580. type: 'image/svg+xml'
  581. });
  582. }
  583. },
  584. downloadPDF: {
  585. textKey: 'downloadPDF',
  586. onclick: function () {
  587. this.exportChartLocal({
  588. type: 'application/pdf'
  589. });
  590. }
  591. }
  592. }
  593. });
  594. // Compatibility
  595. H.downloadSVGLocal = downloadSVGLocal;