Web Workers

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

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 }); } import 'bootstrap.css'; import '@grapecity/wijmo.styles/wijmo.css'; import './styles.css'; // import * as chart from '@grapecity/wijmo.chart'; import '@grapecity/wijmo.chart.render'; import * as grid from '@grapecity/wijmo.grid'; import * as pdf from '@grapecity/wijmo.pdf'; import * as gridPdf from '@grapecity/wijmo.grid.pdf'; // import { Component, Inject, enableProdMode, NgModule, OnDestroy, ViewChild } from '@angular/core'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { BrowserModule } from '@angular/platform-browser'; import { IExpense, DataService } from './app.data'; import { WjGridModule } from '@grapecity/wijmo.angular2.grid'; import { WjChartModule } from '@grapecity/wijmo.angular2.chart'; // interface IContext { exporting: boolean, progress: number, preparing: boolean, worker: Worker } // @Component({ selector: 'app-component', templateUrl: 'src/app.component.html' }) export class AppComponent implements OnDestroy { private readonly docName = 'FlexGrid.pdf'; private readonly gridExportSettings: gridPdf.IFlexGridExportSettings = { styles: { cellStyle: { backgroundColor: '#ffffff', borderColor: '#c6c6c6' }, altCellStyle: { backgroundColor: '#f9f9f9' }, groupCellStyle: { backgroundColor: '#dddddd' }, headerCellStyle: { backgroundColor: '#eaeaea' } } }; // data: any[]; totals: any; // constructor(@Inject(DataService) private dataService: DataService) { this.data = dataService.getData(1500); // this.totals = ((totals: IExpense) => [ { 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 } ])(dataService.getExpenses().totals); } // // @ViewChild('flexGrid') flexGrid: grid.FlexGrid; ctx1: IContext = { exporting: false, progress: 0, preparing: false, worker: null }; // export1(ctx: IContext) { if (!ctx.exporting) { this.start(ctx, './export-grid', () => { gridPdf.PdfWebWorkerClient.exportGrid(ctx.worker, this.flexGrid, this.docName, this.gridExportSettings, null, (progress: number) => { this.progress(ctx, progress); }); }); } else { this.cancel(ctx); } } // // @ViewChild('flexGrid2') flexGrid2: grid.FlexGrid; @ViewChild('flexPie') flexPie: chart.FlexPie; ctx2: IContext = { exporting: false, progress: 0, preparing: false, worker: null }; // export2(ctx: IContext) { if (!ctx.exporting) { this.start(ctx, './export', () => { gridPdf.PdfWebWorkerClient.addString(ctx.worker, 'Title', 'title'); gridPdf.PdfWebWorkerClient.addImage(ctx.worker, 'resources/canada.png', 'flag', null); this.flexPie.saveImageToDataUrl(chart.ImageFormat.Svg, (url: string) => { gridPdf.PdfWebWorkerClient.addImage(ctx.worker, url, 'chart', null); }); gridPdf.PdfWebWorkerClient.addGrid(ctx.worker, this.flexGrid2, 'grid', this.gridExportSettings); // gridPdf.PdfWebWorkerClient.export(ctx.worker, null, (data: gridPdf.PdfWebWorkerExportDoneEventArgs) => pdf.saveBlob(data.blob, this.docName), (progress: number) => this.progress(ctx, progress) ); }); } else { this.cancel(ctx); } } // // @ViewChild('flexGrid3') flexGrid3: grid.FlexGrid; ctx3: IContext = { exporting: false, progress: 0, preparing: false, worker: null }; // export3(ctx: IContext) { if (!ctx.exporting) { this.start(ctx, './api', () => { ctx.worker.addEventListener('message', (e) => { if (e.data.type === 'progress') { this.progress(ctx, e.data.value); } else { pdf.saveBlob(new Blob([new Uint8Array(e.data.data)], { type: 'application/pdf' }), this.docName); } }); // var gridData = gridPdf.PdfWebWorkerClient.serializeGrid(this.flexGrid3, this.gridExportSettings); // Send gridData as a tranferable object ctx.worker.postMessage({ grid: gridData, settings: JSON.stringify(this.gridExportSettings) }, [gridData]); }); } else { this.cancel(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 */ private loadWorker(url: string, ready: Function) { let worker = new Worker('src/workers/worker-loader.js'); // worker.addEventListener('message', (e) => { if (e.data === '#ready#') { ready(); } }); // worker.postMessage({ url: url }); // return worker; } // private start(ctx: IContext, url: string, ready: Function) { ctx.preparing = true; ctx.progress = 0; ctx.worker = this.loadWorker(url, () => ready()); } // private progress(ctx: IContext, progress: number) { if (progress === 0 || progress === 1) { ctx.preparing = false; ctx.exporting = progress === 0; } ctx.progress = progress; } // private cancel(ctx: IContext) { ctx.worker.terminate(); ctx.exporting = false; ctx.progress = 0; ctx.worker = null; } // ngOnDestroy() { if (this.ctx1.worker) { this.ctx1.worker.terminate(); this.ctx1.worker = null; } // if (this.ctx2.worker) { this.ctx2.worker.terminate(); this.ctx2.worker = null; } // if (this.ctx3.worker) { this.ctx3.worker.terminate(); this.ctx3.worker = null; } } } // @NgModule({ imports: [WjGridModule, WjChartModule, BrowserModule], declarations: [AppComponent], providers: [DataService], bootstrap: [AppComponent] }) export class AppModule { } // enableProdMode(); // Bootstrap application with hash style navigation and global services. platformBrowserDynamic().bootstrapModule(AppModule); <!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"> <!-- Polyfills --> <script src="node_modules/core-js/client/shim.min.js"></script> <script src="node_modules/zone.js/dist/zone.min.js"></script> <!-- SystemJS --> <script src="node_modules/systemjs/dist/system.js"></script> <script src="systemjs.config.js"></script> <script> // workaround to load 'rxjs/operators' from the rxjs bundle System.import('rxjs').then(function (m) { System.set(SystemJS.resolveSync('rxjs/operators'), System.newModule(m.operators)); System.import('./src/app.component'); }); </script> </head> <body> <app-component></app-component> </body> </html> <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" [disabled]="ctx1.preparing" (click)="export1(ctx1)">{{ctx1.exporting ? 'Cancel' : 'Export'}}</button>&nbsp; <span>{{ ctx1.progress | percent:'1.1-1' }}</span> <wj-flex-grid class="grid" #flexGrid [autoGenerateColumns]="false" headersVisibility="Column" allowMerging="All" [itemsSource]="data" [isDisabled]="ctx1.preparing"> <wj-flex-grid-column header="ID" binding="id"></wj-flex-grid-column> <wj-flex-grid-column header="Start Date" binding="start" format="d"></wj-flex-grid-column> <wj-flex-grid-column header="End Date" binding="end" format="d"></wj-flex-grid-column> <wj-flex-grid-column header="Country" binding="country"></wj-flex-grid-column> <wj-flex-grid-column header="Product" binding="product"></wj-flex-grid-column> <wj-flex-grid-column header="Amount" binding="amount" format="c"></wj-flex-grid-column> <wj-flex-grid-column header="Color" binding="color"></wj-flex-grid-column> <wj-flex-grid-column header="Pending" binding="amount2" format="c2"></wj-flex-grid-column> <wj-flex-grid-column header="Discount" binding="discount" format="p1"></wj-flex-grid-column> <wj-flex-grid-column header="Active" binding="active"></wj-flex-grid-column> </wj-flex-grid> <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" [disabled]="ctx2.preparing" (click)="export2(ctx2)">{{ctx2.exporting ? 'Cancel' : 'Export'}}</button>&nbsp; <span>{{ ctx2.progress | percent:'1.1-1' }}</span> <p></p> <div class="row"> <div class="col-md-6"> <wj-flex-pie #flexPie [itemsSource]="totals" binding="value" bindingName="name" [innerRadius]="0.75"> <wj-flex-pie-data-label content="{value:c1}" position="Inside"></wj-flex-pie-data-label> </wj-flex-pie> </div> <div class="col-md-6"> <wj-flex-grid class="grid" #flexGrid2 [autoGenerateColumns]="false" headersVisibility="Column" allowMerging="All" [itemsSource]="data" [isDisabled]="ctx2.preparing"> <wj-flex-grid-column header="ID" binding="id"></wj-flex-grid-column> <wj-flex-grid-column header="Start Date" binding="start" format="d"></wj-flex-grid-column> <wj-flex-grid-column header="End Date" binding="end" format="d"></wj-flex-grid-column> <wj-flex-grid-column header="Country" binding="country"></wj-flex-grid-column> <wj-flex-grid-column header="Product" binding="product"></wj-flex-grid-column> <wj-flex-grid-column header="Amount" binding="amount" format="c"></wj-flex-grid-column> <wj-flex-grid-column header="Color" binding="color"></wj-flex-grid-column> <wj-flex-grid-column header="Pending" binding="amount2" format="c2"></wj-flex-grid-column> <wj-flex-grid-column header="Discount" binding="discount" format="p1"></wj-flex-grid-column> <wj-flex-grid-column header="Active" binding="active"></wj-flex-grid-column> </wj-flex-grid> </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" [disabled]="ctx3.preparing" (click)="export3(ctx3)">{{ctx3.exporting ? 'Cancel' : 'Export'}}</button>&nbsp; <span>{{ ctx3.progress | percent:'1.1-1' }}</span> <wj-flex-grid class="grid" #flexGrid3 [autoGenerateColumns]="false" headersVisibility="Column" allowMerging="All" [itemsSource]="data" [isDisabled]="ctx3.preparing"> <wj-flex-grid-column header="ID" binding="id"></wj-flex-grid-column> <wj-flex-grid-column header="Start Date" binding="start" format="d"></wj-flex-grid-column> <wj-flex-grid-column header="End Date" binding="end" format="d"></wj-flex-grid-column> <wj-flex-grid-column header="Country" binding="country"></wj-flex-grid-column> <wj-flex-grid-column header="Product" binding="product"></wj-flex-grid-column> <wj-flex-grid-column header="Amount" binding="amount" format="c"></wj-flex-grid-column> <wj-flex-grid-column header="Color" binding="color"></wj-flex-grid-column> <wj-flex-grid-column header="Pending" binding="amount2" format="c2"></wj-flex-grid-column> <wj-flex-grid-column header="Discount" binding="discount" format="p1"></wj-flex-grid-column> <wj-flex-grid-column header="Active" binding="active"></wj-flex-grid-column> </wj-flex-grid> </div> import { Injectable } from '@angular/core'; // export interface IExpense { hotel: number; transport: number; fuel: number; meal: number; Misc: number; total: number; } // export interface IExpenseDetails extends IExpense { date: Date; description: string; } // export interface IExpenses { items: IExpenseDetails[]; totals: IExpense; } // @Injectable() export class DataService { getData(count: number) { // 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; } // getExpenses(): IExpenses { // [5; 10] let count = 5 + Math.round(Math.random() * 5), ret: IExpenses = { 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: IExpenseDetails = { 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 xmldom from 'xmldom'; import * as pdf from '@grapecity/wijmo.pdf'; import * as gridPdf from '@grapecity/wijmo.grid.pdf'; // (<any>self).DOMParser = xmldom.DOMParser; // gridPdf.PdfWebWorker.initExport((doc: pdf.PdfDocument, clientData: gridPdf.IClientData) => { 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: number) => { // 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: number, inMin: number, inMax: number, outMin: number, outMax: number) { let k = (outMax - outMin) / (inMax - inMin); return (value - inMin) * k + outMin; } declare function postMessage(message: any, transfer?: Transferable[]): void; // 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: pdf.PdfDocument, args: pdf.PdfDocumentEndedEventArgs) => { postProgress(1); // 100% // // Convert Blob to a transferable object... let fileReader = new FileReader(); fileReader.onload = (e) => { let buffer = (<any>e.target).result; // ...and send it to client. postMessage({ data: buffer }, [buffer]); }; fileReader.readAsArrayBuffer(args.blob); }; // settings.progress = (value: number) => { 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: number) { postMessage({ type: 'progress', value: value }); } <template> <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" :disabled="ctx1.preparing" @click="export1(ctx1)">{{ctx1.exporting ? 'Cancel' : 'Export'}}</button>&nbsp; <span>{{ (ctx1.progress * 100).toFixed(1) + "%" }}</span> <wj-flex-grid class="grid" :autoGenerateColumns=false headersVisibility="Column" allowMerging="All" :itemsSource="data" :isDisabled="ctx1.preparing" :initialized="initializeGrid"> <wj-flex-grid-column header="ID" binding="id"></wj-flex-grid-column> <wj-flex-grid-column header="Start Date" binding="start" format="d"></wj-flex-grid-column> <wj-flex-grid-column header="End Date" binding="end" format="d"></wj-flex-grid-column> <wj-flex-grid-column header="Country" binding="country"></wj-flex-grid-column> <wj-flex-grid-column header="Product" binding="product"></wj-flex-grid-column> <wj-flex-grid-column header="Amount" binding="amount" format="c"></wj-flex-grid-column> <wj-flex-grid-column header="Color" binding="color"></wj-flex-grid-column> <wj-flex-grid-column header="Pending" binding="amount2" format="c2"></wj-flex-grid-column> <wj-flex-grid-column header="Discount" binding="discount" format="p1"></wj-flex-grid-column> <wj-flex-grid-column header="Active" binding="active"></wj-flex-grid-column> </wj-flex-grid> <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" :disabled="ctx2.preparing" @click="export2(ctx2)">{{ctx2.exporting ? 'Cancel' : 'Export'}}</button>&nbsp; <span>{{ (ctx2.progress * 100).toFixed(1) + "%" }}</span> <p></p> <div class="row"> <div class="col-md-6"> <wj-flex-pie :itemsSource="totals" binding="value" bindingName="name" :innerRadius="0.75" :initialized="initializePie"> <wj-flex-pie-data-label content="{value:c1}" position="Inside"></wj-flex-pie-data-label> </wj-flex-pie> </div> <div class="col-md-6"> <wj-flex-grid class="grid" :autoGenerateColumns=false headersVisibility="Column" allowMerging="All" :itemsSource="data" :isDisabled="ctx2.preparing" :initialized="initializeGrid2"> <wj-flex-grid-column header="ID" binding="id"></wj-flex-grid-column> <wj-flex-grid-column header="Start Date" binding="start" format="d"></wj-flex-grid-column> <wj-flex-grid-column header="End Date" binding="end" format="d"></wj-flex-grid-column> <wj-flex-grid-column header="Country" binding="country"></wj-flex-grid-column> <wj-flex-grid-column header="Product" binding="product"></wj-flex-grid-column> <wj-flex-grid-column header="Amount" binding="amount" format="c"></wj-flex-grid-column> <wj-flex-grid-column header="Color" binding="color"></wj-flex-grid-column> <wj-flex-grid-column header="Pending" binding="amount2" format="c2"></wj-flex-grid-column> <wj-flex-grid-column header="Discount" binding="discount" format="p1"></wj-flex-grid-column> <wj-flex-grid-column header="Active" binding="active"></wj-flex-grid-column> </wj-flex-grid> </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" :disabled="ctx3.preparing" @click="export3(ctx3)">{{ctx3.exporting ? 'Cancel' : 'Export'}}</button>&nbsp; <span>{{ (ctx3.progress * 100).toFixed(1) + "%" }}</span> <wj-flex-grid class="grid" :autoGenerateColumns=false headersVisibility="Column" allowMerging="All" :itemsSource="data" :isDisabled="ctx3.preparing" :initialized="initializeGrid3"> <wj-flex-grid-column header="ID" binding="id"></wj-flex-grid-column> <wj-flex-grid-column header="Start Date" binding="start" format="d"></wj-flex-grid-column> <wj-flex-grid-column header="End Date" binding="end" format="d"></wj-flex-grid-column> <wj-flex-grid-column header="Country" binding="country"></wj-flex-grid-column> <wj-flex-grid-column header="Product" binding="product"></wj-flex-grid-column> <wj-flex-grid-column header="Amount" binding="amount" format="c"></wj-flex-grid-column> <wj-flex-grid-column header="Color" binding="color"></wj-flex-grid-column> <wj-flex-grid-column header="Pending" binding="amount2" format="c2"></wj-flex-grid-column> <wj-flex-grid-column header="Discount" binding="discount" format="p1"></wj-flex-grid-column> <wj-flex-grid-column header="Active" binding="active"></wj-flex-grid-column> </wj-flex-grid> </div> </template> <script> import 'bootstrap.css'; import '@grapecity/wijmo.styles/wijmo.css'; import Vue from 'vue'; 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 { getExpenses, getData } from './data'; import { WjGridModule } from '@grapecity/wijmo.vue2.grid'; import { WjChartModule } from '@grapecity/wijmo.vue2.chart'; new Vue({ el: '#app', data: { docName: 'FlexGrid.pdf', gridExportSettings: { styles: { cellStyle: { backgroundColor: '#ffffff', borderColor: '#c6c6c6' }, altCellStyle: { backgroundColor: '#f9f9f9' }, groupCellStyle: { backgroundColor: '#dddddd' }, headerCellStyle: { backgroundColor: '#eaeaea' } } }, data: getData(1500), totals: ((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), ctx1: { exporting: false, progress: 0, preparing: false, worker: null }, ctx2: { exporting: false, progress: 0, preparing: false, worker: null }, ctx3: { exporting: false, progress: 0, preparing: false, worker: null } }, methods: { initializeGrid(ctl) { this.flexGrid = ctl; }, initializeGrid2(ctl) { this.flexGrid2 = ctl; }, initializeGrid3(ctl) { this.flexGrid3 = ctl; }, initializePie(ctl) { this.flexPie = ctl; }, export1(ctx) { if (!ctx.exporting) { this.start(ctx, './export-grid.js', () => { gridPdf.PdfWebWorkerClient.exportGrid(ctx.worker, this.flexGrid, this.docName, this.gridExportSettings, null, (progress) => { this.progress(ctx, progress); }); }); } else { this.cancel(ctx); } }, export2(ctx) { if (!ctx.exporting) { this.start(ctx, './export.js', () => { gridPdf.PdfWebWorkerClient.addString(ctx.worker, 'Title', 'title'); gridPdf.PdfWebWorkerClient.addImage(ctx.worker, 'resources/canada.png', 'flag', null); this.flexPie.saveImageToDataUrl(chart.ImageFormat.Svg, (url) => { gridPdf.PdfWebWorkerClient.addImage(ctx.worker, url, 'chart', null); }); gridPdf.PdfWebWorkerClient.addGrid(ctx.worker, this.flexGrid2, 'grid', this.gridExportSettings); // gridPdf.PdfWebWorkerClient.export(ctx.worker, null, (data) => pdf.saveBlob(data.blob, this.docName), (progress) => this.progress(ctx, progress) ); }); } else { this.cancel(ctx); } }, export3(ctx) { if (!ctx.exporting) { this.start(ctx, './api.js', () => { ctx.worker.addEventListener('message', (e) => { if (e.data.type === 'progress') { this.progress(ctx, e.data.value); } else { pdf.saveBlob(new Blob([new Uint8Array(e.data.data)], { type: 'application/pdf' }), this.docName); } }); // var gridData = gridPdf.PdfWebWorkerClient.serializeGrid(this.flexGrid3, this.gridExportSettings); // Send gridData as a tranferable object ctx.worker.postMessage({ grid: gridData, settings: JSON.stringify(this.gridExportSettings) }, [gridData]); }); } else { this.cancel(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 */ 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; }, start(ctx, url, ready) { ctx.preparing = true; ctx.progress = 0; ctx.worker = this.loadWorker(url, () => ready()); }, progress(ctx, progress) { if (progress === 0 || progress === 1) { ctx.preparing = false; ctx.exporting = progress === 0; } ctx.progress = progress; }, cancel(ctx) { ctx.worker.terminate(); ctx.exporting = false; ctx.progress = 0; ctx.worker = null; } }, destroyed: function() { if (this.ctx1.worker) { this.ctx1.worker.terminate(); this.ctx1.worker = null; } if (this.ctx2.worker) { this.ctx2.worker.terminate(); this.ctx2.worker = null; } if (this.ctx3.worker) { this.ctx3.worker.terminate(); this.ctx3.worker = null; } } }); </script> <style> body { margin-bottom: 24px; } .grid { margin-top: 20px; height: 300px; } </style> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>AutoComplete</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.vue'); </script> </head> <body> <div id="app"> </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; } import { PdfWebWorker } from '@grapecity/wijmo.grid.pdf'; // PdfWebWorker.initExportGrid(); import 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 }); } import "@grapecity/wijmo.styles/wijmo.css"; import "bootstrap.css"; import "./app.css"; // import * as React from 'react'; import * as ReactDOM from 'react-dom'; import * as chart from '@grapecity/wijmo.chart'; import * as pdf from '@grapecity/wijmo.pdf'; import * as gridPdf from '@grapecity/wijmo.grid.pdf'; import '@grapecity/wijmo.chart.render'; // import * as wjcGrid from '@grapecity/wijmo.react.grid'; import * as WjChartModule from '@grapecity/wijmo.react.chart'; import { getExpenses, getData } from './data'; // class App extends React.Component { // constructor(props) { super(props); // this._docName = 'FlexGrid.pdf'; this._data = getData(1500); this._totals = ((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); // this._gridExportSettings = { styles: { cellStyle: { backgroundColor: '#ffffff', borderColor: '#c6c6c6' }, altCellStyle: { backgroundColor: '#f9f9f9' }, groupCellStyle: { backgroundColor: '#dddddd' }, headerCellStyle: { backgroundColor: '#eaeaea' } } }; // this.state = { ctx1: { exporting: false, progress: 0, preparing: false, worker: null }, ctx2: { exporting: false, progress: 0, preparing: false, worker: null }, ctx3: { exporting: false, progress: 0, preparing: false, worker: null } }; } // render() { return <div className="container-fluid"> <p> This sample demonstrates the "Simple single grid export" scenario and shows how to export FlexGrid in a background thread. </p> <button className="btn btn-default" disabled={this.state.ctx1.preparing} onClick={this.export1.bind(this, this.state.ctx1)}>{this.state.ctx1.exporting ? 'Cancel' : 'Export'}</button>&nbsp; <span>{(this.state.ctx1.progress * 100).toFixed(1) + "%"}</span> <wjcGrid.FlexGrid className="grid" autoGenerateColumns={false} headersVisibility="Column" allowMerging="All" itemsSource={this._data} isDisabled={this.state.ctx1.preparing} initialized={this.initializeGrid.bind(this)}> <wjcGrid.FlexGridColumn header="ID" binding="id"></wjcGrid.FlexGridColumn> <wjcGrid.FlexGridColumn header="Start Date" binding="start" format="d"></wjcGrid.FlexGridColumn> <wjcGrid.FlexGridColumn header="End Date" binding="end" format="d"></wjcGrid.FlexGridColumn> <wjcGrid.FlexGridColumn header="Country" binding="country"></wjcGrid.FlexGridColumn> <wjcGrid.FlexGridColumn header="Product" binding="product"></wjcGrid.FlexGridColumn> <wjcGrid.FlexGridColumn header="Amount" binding="amount" format="c"></wjcGrid.FlexGridColumn> <wjcGrid.FlexGridColumn header="Color" binding="color"></wjcGrid.FlexGridColumn> <wjcGrid.FlexGridColumn header="Pending" binding="amount2" format="c2"></wjcGrid.FlexGridColumn> <wjcGrid.FlexGridColumn header="Discount" binding="discount" format="p1"></wjcGrid.FlexGridColumn> <wjcGrid.FlexGridColumn header="Active" binding="active"></wjcGrid.FlexGridColumn> </wjcGrid.FlexGrid> <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 className="btn btn-default" disabled={this.state.ctx2.preparing} onClick={this.export2.bind(this, this.state.ctx2)}>{this.state.ctx2.exporting ? 'Cancel' : 'Export'}</button>&nbsp; <span>{(this.state.ctx2.progress * 100).toFixed(1) + "%"}</span> <p></p> <div className="row"> <div className="col-md-6"> <WjChartModule.FlexPie itemsSource={this._totals} binding="value" bindingName="name" innerRadius={0.75} initialized={this.initializePie.bind(this)}> <WjChartModule.FlexPieDataLabel content="{value:c1}" position="Inside"></WjChartModule.FlexPieDataLabel> </WjChartModule.FlexPie> </div> <div className="col-md-6"> <wjcGrid.FlexGrid className="grid" autoGenerateColumns={false} headersVisibility="Column" allowMerging="All" itemsSource={this._data} isDisabled={this.state.ctx2.preparing} initialized={this.initializeGrid2.bind(this)}> <wjcGrid.FlexGridColumn header="ID" binding="id"></wjcGrid.FlexGridColumn> <wjcGrid.FlexGridColumn header="Start Date" binding="start" format="d"></wjcGrid.FlexGridColumn> <wjcGrid.FlexGridColumn header="End Date" binding="end" format="d"></wjcGrid.FlexGridColumn> <wjcGrid.FlexGridColumn header="Country" binding="country"></wjcGrid.FlexGridColumn> <wjcGrid.FlexGridColumn header="Product" binding="product"></wjcGrid.FlexGridColumn> <wjcGrid.FlexGridColumn header="Amount" binding="amount" format="c"></wjcGrid.FlexGridColumn> <wjcGrid.FlexGridColumn header="Color" binding="color"></wjcGrid.FlexGridColumn> <wjcGrid.FlexGridColumn header="Pending" binding="amount2" format="c2"></wjcGrid.FlexGridColumn> <wjcGrid.FlexGridColumn header="Discount" binding="discount" format="p1"></wjcGrid.FlexGridColumn> <wjcGrid.FlexGridColumn header="Active" binding="active"></wjcGrid.FlexGridColumn> </wjcGrid.FlexGrid> </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 className="btn btn-default" disabled={this.state.ctx3.preparing} onClick={this.export3.bind(this, this.state.ctx3)}>{this.state.ctx3.exporting ? 'Cancel' : 'Export'}</button>&nbsp; <span>{(this.state.ctx3.progress * 100).toFixed(1) + "%"}</span> <p></p> <wjcGrid.FlexGrid className="grid" autoGenerateColumns={false} headersVisibility="Column" allowMerging="All" itemsSource={this._data} isDisabled={this.state.ctx3.preparing} initialized={this.initializeGrid3.bind(this)}> <wjcGrid.FlexGridColumn header="ID" binding="id"></wjcGrid.FlexGridColumn> <wjcGrid.FlexGridColumn header="Start Date" binding="start" format="d"></wjcGrid.FlexGridColumn> <wjcGrid.FlexGridColumn header="End Date" binding="end" format="d"></wjcGrid.FlexGridColumn> <wjcGrid.FlexGridColumn header="Country" binding="country"></wjcGrid.FlexGridColumn> <wjcGrid.FlexGridColumn header="Product" binding="product"></wjcGrid.FlexGridColumn> <wjcGrid.FlexGridColumn header="Amount" binding="amount" format="c"></wjcGrid.FlexGridColumn> <wjcGrid.FlexGridColumn header="Color" binding="color"></wjcGrid.FlexGridColumn> <wjcGrid.FlexGridColumn header="Pending" binding="amount2" format="c2"></wjcGrid.FlexGridColumn> <wjcGrid.FlexGridColumn header="Discount" binding="discount" format="p1"></wjcGrid.FlexGridColumn> <wjcGrid.FlexGridColumn header="Active" binding="active"></wjcGrid.FlexGridColumn> </wjcGrid.FlexGrid> </div>; } // initializeGrid(source) { this._grid1 = source; } // initializeGrid2(source) { this._grid2 = source; } // initializeGrid3(source) { this._grid3 = source; } // initializePie(source) { this._pie = source; } // export1(ctx) { if (!ctx.exporting) { this.start(ctx, './export-grid.js', () => { gridPdf.PdfWebWorkerClient.exportGrid(ctx.worker, this._grid1, this._docName, this._gridExportSettings, null, (progress) => { this.progress(ctx, progress); }); }); } else { this.cancel(ctx); } } // export2(ctx) { if (!ctx.exporting) { this.start(ctx, './export.js', () => { gridPdf.PdfWebWorkerClient.addString(ctx.worker, 'Title', 'title'); gridPdf.PdfWebWorkerClient.addImage(ctx.worker, 'resources/canada.png', 'flag', null); this._pie.saveImageToDataUrl(chart.ImageFormat.Svg, (url) => { gridPdf.PdfWebWorkerClient.addImage(ctx.worker, url, 'chart', null); }); gridPdf.PdfWebWorkerClient.addGrid(ctx.worker, this._grid2, 'grid', this._gridExportSettings); gridPdf.PdfWebWorkerClient.export(ctx.worker, null, (data) => pdf.saveBlob(data.blob, this._docName), (progress) => this.progress(ctx, progress)); }); } else { this.cancel(ctx); } } // export3(ctx) { if (!ctx.exporting) { this.start(ctx, './api.js', () => { ctx.worker.addEventListener('message', e => { if (e.data.type === 'progress') { this.progress(ctx, e.data.value); } else { pdf.saveBlob(new Blob([new Uint8Array(e.data.data)], { type: 'application/pdf' }), this._docName); } }); let gridData = gridPdf.PdfWebWorkerClient.serializeGrid(this._grid3, this._gridExportSettings); // Send gridData as a tranferable object ctx.worker.postMessage({ grid: gridData, settings: JSON.stringify(this._gridExportSettings) }, [gridData]); }); } else { this.cancel(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 */ 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; } // start(ctx, url, ready) { this.setState((state) => { ctx.preparing = true; ctx.progress = 0; ctx.worker = this.loadWorker(url, () => ready()); return state; }); } // progress(ctx, progress) { if (progress === 0 || progress === 1) { this.setState((state) => { ctx.preparing = false; ctx.exporting = progress === 0; ctx.progress = progress; return state; }); } else { this.setState((state) => { ctx.progress = progress; return state; }); } } // cancel(ctx) { this.setState((state) => { ctx.worker.terminate(); ctx.exporting = false; ctx.progress = 0; ctx.worker = null; return state; }); } // componentWillUnmount() { if (this.state.ctx1.worker) { this.state.ctx1.worker.terminate(); this.state.ctx1.worker = null; } if (this.state.ctx2.worker) { this.state.ctx2.worker.terminate(); this.state.ctx2.worker = null; } if (this.state.ctx3.worker) { this.state.ctx3.worker.terminate(); this.state.ctx3.worker = null; } } } // ReactDOM.render(<App />, document.getElementById('app')); <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Grapecity Wijmo OLAP Pivot Chart Overview</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 id="app"></div> </body> </html> body { margin-bottom: 24px; } .grid { margin-top: 20px; height: 300px; } 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; } import { PdfWebWorker } from '@grapecity/wijmo.grid.pdf'; // PdfWebWorker.initExportGrid(); import xmldom from 'xmldom'; import * as pdf from '@grapecity/wijmo.pdf'; import * as gridPdf from '@grapecity/wijmo.grid.pdf'; // (<any>self).DOMParser = xmldom.DOMParser; // gridPdf.PdfWebWorker.initExport((doc: pdf.PdfDocument, clientData: gridPdf.IClientData) => { 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: number) => { // 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: number, inMin: number, inMax: number, outMin: number, outMax: number) { let k = (outMax - outMin) / (inMax - inMin); return (value - inMin) * k + outMin; } declare function postMessage(message: any, transfer?: Transferable[]): void; 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: pdf.PdfDocument, args: pdf.PdfDocumentEndedEventArgs) => { postProgress(1); // 100% // // Convert Blob to a transferable object... let fileReader = new FileReader(); fileReader.onload = (e) => { let buffer = (<any>e.target).result; // ...and send it to client. postMessage({ data: buffer }, [buffer]); }; fileReader.readAsArrayBuffer(args.blob); }; // settings.progress = (value: number) => { 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 }); }