Web Workers

This sample demonstrates how to use Web Workers to export FlexGrid to a PDF or generate a custom PDF in a background thread.

Learn about FlexGrid | FlexGrid API Reference

import 'bootstrap.css'; import '@grapecity/wijmo.styles/wijmo.css'; import './styles.css'; import * as wijmo from '@grapecity/wijmo'; import * as grid from '@grapecity/wijmo.grid'; import * as chart from '@grapecity/wijmo.chart'; import '@grapecity/wijmo.chart.render'; import * as pdf from '@grapecity/wijmo.pdf'; import * as gridPdf from '@grapecity/wijmo.grid.pdf'; import { getData, getExpenses } from './data'; // document.readyState === 'complete' ? init() : window.onload = init; const docName = 'FlexGrid.pdf'; // function init() { const exportSettings = { styles: { cellStyle: { backgroundColor: '#ffffff', borderColor: '#c6c6c6' }, altCellStyle: { backgroundColor: '#f9f9f9' }, groupCellStyle: { backgroundColor: '#dddddd' }, headerCellStyle: { backgroundColor: '#eaeaea' } } }; const data = getData(1500); // initExportGridSample(exportSettings, data); initExportSample(exportSettings, data); initApiSample(exportSettings, data); } // // function initExportGridSample(exportSettings, data) { let flexGrid = new grid.FlexGrid('#flexGrid1', { autoGenerateColumns: false, selectionMode: grid.SelectionMode.ListBox, headersVisibility: grid.HeadersVisibility.All, columns: [ { header: 'ID', binding: 'id' }, { header: 'Start Date', binding: 'start', format: 'd' }, { header: 'End Date', binding: 'end', format: 'd' }, { header: 'Country', binding: 'country' }, { header: 'Product', binding: 'product' }, { header: 'Amount', binding: 'amount', format: 'c' }, { header: 'Color', binding: 'color' }, { header: 'Pending', binding: 'amount2', format: 'c2' }, { header: 'Discount', binding: 'discount', format: 'p1' }, { header: 'Active', binding: 'active' } ], itemsSource: data }); // let ctx = { exporting: false, progress: 0, preparing: false, worker: null, grid: flexGrid, button: document.querySelector('#btnExport1'), progressEl: document.querySelector('#txtProgress1') }; // ctx.button.addEventListener('click', () => { if (!ctx.exporting) { start(ctx, './export-grid', () => { gridPdf.PdfWebWorkerClient.exportGrid(ctx.worker, flexGrid, docName, exportSettings, null, (prgVal) => { progress(ctx, prgVal); }); }); } else { cancel(ctx); } }); // window.addEventListener('unload', () => { if (ctx.worker) { ctx.worker.terminate(); ctx.worker = null; } }); } // // function initExportSample(exportSettings, data) { let flexPie = new chart.FlexPie('#flexPie', { itemsSource: ((totals) => [ { name: 'Hotel', value: totals.hotel }, { name: 'Transport', value: totals.transport }, { name: 'Meal', value: totals.meal }, { name: 'Fuel', value: totals.fuel }, { name: 'Misc', value: totals.Misc } ])(getExpenses().totals), binding: 'value', bindingName: 'name', innerRadius: 0.75, dataLabel: { content: '{value:c1}', position: chart.PieLabelPosition.Inside } }); // let flexGrid = new grid.FlexGrid('#flexGrid2', { autoGenerateColumns: false, selectionMode: grid.SelectionMode.ListBox, headersVisibility: grid.HeadersVisibility.All, columns: [ { header: 'ID', binding: 'id' }, { header: 'Start Date', binding: 'start', format: 'd' }, { header: 'End Date', binding: 'end', format: 'd' }, { header: 'Country', binding: 'country' }, { header: 'Product', binding: 'product' }, { header: 'Amount', binding: 'amount', format: 'c' }, { header: 'Color', binding: 'color' }, { header: 'Pending', binding: 'amount2', format: 'c2' }, { header: 'Discount', binding: 'discount', format: 'p1' }, { header: 'Active', binding: 'active' } ], itemsSource: data }); // let ctx = { exporting: false, progress: 0, preparing: false, worker: null, grid: flexGrid, button: document.querySelector('#btnExport2'), progressEl: document.querySelector('#txtProgress2') }; // ctx.button.addEventListener('click', () => { if (!ctx.exporting) { start(ctx, './export', () => { gridPdf.PdfWebWorkerClient.addString(ctx.worker, 'Title', 'title'); gridPdf.PdfWebWorkerClient.addImage(ctx.worker, 'resources/canada.png', 'flag', null); flexPie.saveImageToDataUrl(chart.ImageFormat.Svg, (url) => { gridPdf.PdfWebWorkerClient.addImage(ctx.worker, url, 'chart', null); }); gridPdf.PdfWebWorkerClient.addGrid(ctx.worker, flexGrid, 'grid', exportSettings); // gridPdf.PdfWebWorkerClient.export(ctx.worker, null, (data) => pdf.saveBlob(data.blob, docName), (prgVal) => progress(ctx, prgVal)); }); } else { cancel(ctx); } }); // window.addEventListener('unload', () => { if (ctx.worker) { ctx.worker.terminate(); ctx.worker = null; } }); } // // function initApiSample(exportSettings, data) { let flexGrid = new grid.FlexGrid('#flexGrid3', { autoGenerateColumns: false, selectionMode: grid.SelectionMode.ListBox, headersVisibility: grid.HeadersVisibility.All, columns: [ { header: 'ID', binding: 'id' }, { header: 'Start Date', binding: 'start', format: 'd' }, { header: 'End Date', binding: 'end', format: 'd' }, { header: 'Country', binding: 'country' }, { header: 'Product', binding: 'product' }, { header: 'Amount', binding: 'amount', format: 'c' }, { header: 'Color', binding: 'color' }, { header: 'Pending', binding: 'amount2', format: 'c2' }, { header: 'Discount', binding: 'discount', format: 'p1' }, { header: 'Active', binding: 'active' } ], itemsSource: data }); // let ctx = { exporting: false, progress: 0, preparing: false, worker: null, grid: flexGrid, button: document.querySelector('#btnExport3'), progressEl: document.querySelector('#txtProgress3') }; // ctx.button.addEventListener('click', () => { if (!ctx.exporting) { start(ctx, './api', () => { ctx.worker.addEventListener('message', (e) => { if (e.data.type === 'progress') { progress(ctx, e.data.value); } else { pdf.saveBlob(new Blob([new Uint8Array(e.data.data)], { type: 'application/pdf' }), docName); } }); // var gridData = gridPdf.PdfWebWorkerClient.serializeGrid(flexGrid, exportSettings); // Send gridData as a tranferable object ctx.worker.postMessage({ grid: gridData, settings: JSON.stringify(exportSettings) }, [gridData]); }); } else { cancel(ctx); } }); // window.addEventListener('unload', () => { if (ctx.worker) { ctx.worker.terminate(); ctx.worker = null; } }); } // function start(ctx, url, ready) { ctx.preparing = true; ctx.progress = 0; updateUI(ctx); // ctx.worker = loadWorker(url, () => ready()); } // function progress(ctx, progress) { if (progress === 0 || progress === 1) { ctx.preparing = false; ctx.exporting = progress === 0; } ctx.progress = progress; // updateUI(ctx); } // function cancel(ctx) { ctx.worker.terminate(); ctx.worker = null; ctx.exporting = false; ctx.progress = 0; // updateUI(ctx); } // /** * Creates web worker that executes the module from the specified URL. * @param url The module URL, relative to the src/workers directory. * @param ready */ function loadWorker(url, ready) { let worker = new Worker('src/workers/worker-loader.js'); // worker.addEventListener('message', (e) => { if (e.data === '#ready#') { ready(); } }); // worker.postMessage({ url: url }); // return worker; } // function updateUI(ctx) { ctx.grid.isDisabled = ctx.preparing; wijmo.enable(ctx.button, !ctx.preparing); ctx.button.textContent = ctx.exporting ? 'Cancel' : 'Export'; ctx.progressEl.textContent = (ctx.progress * 100).toFixed(1) + '%'; }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Web Workers</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- SystemJS --> <script src="node_modules/systemjs/dist/system.src.js"></script> <script src="systemjs.config.js"></script> <script> System.import('./src/app'); </script> </head> <body> <div class="container-fluid"> <p> This sample demonstrates the "Simple single grid export" scenario and shows how to export FlexGrid in a background thread. </p> <button class="btn btn-default" id="btnExport1">Export</button> <span id="txtProgress1">0%</span> <div id="flexGrid1" class="grid"></div> <hr /> <p> This sample demonstrates the "Custom document generation" scenario and shows how to export FlexPie (as a SVG image), FlexGrid and PNG image to a PDF in a background thread. </p> <p> The <a href="https://www.npmjs.com/package/xmldom">xmldom</a> library is used here to bring DOM support to the server to be able to draw SVG. </p> <button class="btn btn-default" id="btnExport2">Export</button> <span id="txtProgress2">0%</span> <p></p> <div class="row"> <div class="col-md-6"> <div id="flexPie"></div> </div> <div class="col-md-6"> <div id="flexGrid2" class="grid"></div> </div> </div> <hr /> <p> This sample demonstrates the "Low-level usage of Web Workers API" scenario and shows how to export FlexGrid to a PDF in a background thread using Web Workers API. </p> <button class="btn btn-default" id="btnExport3">Export</button> <span id="txtProgress3">0%</span> <div id="flexGrid3" class="grid"></div> </div> </body> </html>
export function getData(count) { // data used to generate random items const countries = ['US', 'Germany', 'UK', 'Japan', 'Italy', 'Greece']; const products = ['Widget', 'Gadget', 'Doohickey']; const colors = ['Orange', 'White', 'Red', 'Green', 'Blue']; // let data = []; let dt = new Date(); // // add count items for (let i = 0; i < count; i++) { // constants used to create data items let date = new Date(dt.getFullYear(), i % 12, 25, i % 24, i % 60, i % 60), countryId = Math.floor(Math.random() * countries.length), productId = Math.floor(Math.random() * products.length), colorId = Math.floor(Math.random() * colors.length); // // create the item let item = { id: i, start: date, end: date, country: countries[countryId], product: products[productId], color: colors[colorId], amount: Math.random() * 10000 - 5000, amount2: Math.random() * 10000 - 5000, discount: Math.random() / 4, active: i % 4 == 0, }; // // add the item to the list data.push(item); } return data; } // export function getExpenses() { // [5; 10] let count = 5 + Math.round(Math.random() * 5), ret = { items: [], totals: { hotel: 0, transport: 0, fuel: 0, meal: 0, Misc: 0, total: 0 } }, msPerDay = 1000 * 24 * 60 * 60, curDate = Date.now() - 60 * msPerDay; // for (let i = 0; i < count; i++) { let item = { date: new Date(curDate), description: 'Customer visit', hotel: 30 + Math.random() * 200, transport: 10 + Math.random() * 150, fuel: Math.random() * 50, meal: 30 + Math.random() * 170, Misc: Math.random() * 220, total: 0 }; // item.total = item.hotel + item.transport + item.fuel + item.meal + item.Misc; // ret.totals.fuel += item.fuel; ret.totals.hotel += item.hotel; ret.totals.meal += item.meal; ret.totals.Misc += item.Misc; ret.totals.total += item.total; ret.totals.transport += item.transport; // ret.items.push(item); // curDate += msPerDay * Math.round(Math.random() * 4); } // return ret; }
body { margin-bottom: 24px; } .grid { margin-top: 20px; height: 200px; } .wj-flexpie { height: 250px; }
import { PdfWebWorker } from '@grapecity/wijmo.grid.pdf'; // PdfWebWorker.initExportGrid();
import * as xmldom from 'xmldom'; import * as gridPdf from '@grapecity/wijmo.grid.pdf'; // self.DOMParser = xmldom.DOMParser; // gridPdf.PdfWebWorker.initExport((doc, clientData) => { gridPdf.PdfWebWorker.sendExportProgress(0); // doc.drawText(clientData['title'].content); doc.drawImage(clientData['flag'].content); doc.drawSvg(clientData['chart'].content); // // Suppose that text and images rendering takes 5% of the time. gridPdf.PdfWebWorker.sendExportProgress(0.05); // let gridData = clientData['grid']; gridData.settings.progress = (value) => { // Change progress from 6% to 90%. Left the final 10% for the document finalization, which will start after the doc.end() method is called. gridPdf.PdfWebWorker.sendExportProgress(map(value, 0, 1, 0.06, 0.9)); }; // doc.ended.addHandler(() => { // Document has been created, set progress to 100%. gridPdf.PdfWebWorker.sendExportProgress(1); }); // gridPdf.FlexGridPdfConverter.draw(gridData.content, doc, null, null, gridData.settings); // doc.end(); }); // function map(value, inMin, inMax, outMin, outMax) { let k = (outMax - outMin) / (inMax - inMin); return (value - inMin) * k + outMin; }
// import * as pdf from '@grapecity/wijmo.pdf'; import * as gridPdf from '@grapecity/wijmo.grid.pdf'; // addEventListener('message', (e) => { let json = e.data.grid, settings = JSON.parse(e.data.settings); // settings.documentOptions = settings.documentOptions || {}; // settings.documentOptions.ended = (sender, args) => { postProgress(1); // 100% // // Convert Blob to a transferable object... let fileReader = new FileReader(); fileReader.onload = (e) => { let buffer = e.target.result; // ...and send it to client. postMessage({ data: buffer }, [buffer]); }; fileReader.readAsArrayBuffer(args.blob); }; // settings.progress = (value) => { postProgress(value * 0.9); // 0% to 90% }; // let doc = new pdf.PdfDocument(settings.documentOptions), grid = gridPdf.PdfWebWorker.deserializeGrid(json, settings); // gridPdf.FlexGridPdfConverter.draw(grid, doc, null, null, settings); // doc.end(); }); // function postProgress(value) { postMessage({ type: 'progress', value: value }); }
(function (global) { System.config({ transpiler: 'plugin-babel', babelOptions: { es2015: true }, meta: { '*.css': { loader: 'css' } }, paths: { // paths serve as alias 'npm:': 'node_modules/' }, // map tells the System loader where to look for things map: { 'jszip': 'npm:jszip/dist/jszip.js', '@grapecity/wijmo': 'npm:@grapecity/wijmo/index.js', '@grapecity/wijmo.input': 'npm:@grapecity/wijmo.input/index.js', '@grapecity/wijmo.styles': 'npm:@grapecity/wijmo.styles', '@grapecity/wijmo.cultures': 'npm:@grapecity/wijmo.cultures', '@grapecity/wijmo.chart': 'npm:@grapecity/wijmo.chart/index.js', '@grapecity/wijmo.chart.analytics': 'npm:@grapecity/wijmo.chart.analytics/index.js', '@grapecity/wijmo.chart.animation': 'npm:@grapecity/wijmo.chart.animation/index.js', '@grapecity/wijmo.chart.annotation': 'npm:@grapecity/wijmo.chart.annotation/index.js', '@grapecity/wijmo.chart.finance': 'npm:@grapecity/wijmo.chart.finance/index.js', '@grapecity/wijmo.chart.finance.analytics': 'npm:@grapecity/wijmo.chart.finance.analytics/index.js', '@grapecity/wijmo.chart.hierarchical': 'npm:@grapecity/wijmo.chart.hierarchical/index.js', '@grapecity/wijmo.chart.interaction': 'npm:@grapecity/wijmo.chart.interaction/index.js', '@grapecity/wijmo.chart.radar': 'npm:@grapecity/wijmo.chart.radar/index.js', '@grapecity/wijmo.chart.render': 'npm:@grapecity/wijmo.chart.render/index.js', '@grapecity/wijmo.chart.webgl': 'npm:@grapecity/wijmo.chart.webgl/index.js', '@grapecity/wijmo.chart.map': 'npm:@grapecity/wijmo.chart.map/index.js', '@grapecity/wijmo.gauge': 'npm:@grapecity/wijmo.gauge/index.js', '@grapecity/wijmo.grid': 'npm:@grapecity/wijmo.grid/index.js', '@grapecity/wijmo.grid.detail': 'npm:@grapecity/wijmo.grid.detail/index.js', '@grapecity/wijmo.grid.filter': 'npm:@grapecity/wijmo.grid.filter/index.js', '@grapecity/wijmo.grid.search': 'npm:@grapecity/wijmo.grid.search/index.js', '@grapecity/wijmo.grid.grouppanel': 'npm:@grapecity/wijmo.grid.grouppanel/index.js', '@grapecity/wijmo.grid.multirow': 'npm:@grapecity/wijmo.grid.multirow/index.js', '@grapecity/wijmo.grid.transposed': 'npm:@grapecity/wijmo.grid.transposed/index.js', '@grapecity/wijmo.grid.transposedmultirow': 'npm:@grapecity/wijmo.grid.transposedmultirow/index.js', '@grapecity/wijmo.grid.pdf': 'npm:@grapecity/wijmo.grid.pdf/index.js', '@grapecity/wijmo.grid.sheet': 'npm:@grapecity/wijmo.grid.sheet/index.js', '@grapecity/wijmo.grid.xlsx': 'npm:@grapecity/wijmo.grid.xlsx/index.js', '@grapecity/wijmo.grid.selector': 'npm:@grapecity/wijmo.grid.selector/index.js', '@grapecity/wijmo.grid.cellmaker': 'npm:@grapecity/wijmo.grid.cellmaker/index.js', '@grapecity/wijmo.nav': 'npm:@grapecity/wijmo.nav/index.js', '@grapecity/wijmo.odata': 'npm:@grapecity/wijmo.odata/index.js', '@grapecity/wijmo.olap': 'npm:@grapecity/wijmo.olap/index.js', '@grapecity/wijmo.rest': 'npm:@grapecity/wijmo.rest/index.js', '@grapecity/wijmo.pdf': 'npm:@grapecity/wijmo.pdf/index.js', '@grapecity/wijmo.pdf.security': 'npm:@grapecity/wijmo.pdf.security/index.js', '@grapecity/wijmo.viewer': 'npm:@grapecity/wijmo.viewer/index.js', '@grapecity/wijmo.xlsx': 'npm:@grapecity/wijmo.xlsx/index.js', '@grapecity/wijmo.undo': 'npm:@grapecity/wijmo.undo/index.js', '@grapecity/wijmo.interop.grid': 'npm:@grapecity/wijmo.interop.grid/index.js', '@grapecity/wijmo.touch': 'npm:@grapecity/wijmo.touch/index.js', '@grapecity/wijmo.cloud': 'npm:@grapecity/wijmo.cloud/index.js', '@grapecity/wijmo.barcode': 'npm:@grapecity/wijmo.barcode/index.js', '@grapecity/wijmo.barcode.common': 'npm:@grapecity/wijmo.barcode.common/index.js', '@grapecity/wijmo.barcode.composite': 'npm:@grapecity/wijmo.barcode.composite/index.js', '@grapecity/wijmo.barcode.specialized': 'npm:@grapecity/wijmo.barcode.specialized/index.js', 'jszip': 'npm:jszip/dist/jszip.js', 'bootstrap.css': 'npm:bootstrap/dist/css/bootstrap.min.css', 'css': 'npm:systemjs-plugin-css/css.js', 'plugin-babel': 'npm:systemjs-plugin-babel/plugin-babel.js', 'systemjs-babel-build':'npm:systemjs-plugin-babel/systemjs-babel-browser.js' }, // packages tells the System loader how to load when no filename and/or no extension packages: { src: { defaultExtension: 'js' }, "node_modules": { defaultExtension: 'js' }, } }); })(this);