how to improve the performance of the code? - javascript

I am using the pdfmake library in a project, but its execution takes about 2-3 min.
Is the library normally slow or do I need to improve the performance of my code ?
It is also possible that performances are impacted by the code being executed in chunks, but I am not sure I understand the role of chunks and why they are used.
var docDefinition = {
footer: function (currentPage, pageCount) {
return {
margin: [40, 0, 0, 0],
columns: [{
fontSize: 8,
text: [
{
text: 'Page ' + currentPage.toString() + ' / ' + pageCount,
}
],
}]
};
},
content: contentAry,
styles: {
clsHeader: {
fontSize: 12,
bold: true
},
clsSubHeader: {
fontSize: 10
},
clsTblHeader: {
fillColor: '#9e9e9e',
color: '#FFFFFF'
},
clsImage: {
margin: [0, 40, 0, 0]
},
clsTable: {
fontSize: 8
}
},
defaultStyle: {
alignment: 'justify'
}
}
var doc = printer.createPdfKitDocument(docDefinition);
var chunks = [];
doc.on('readable', function () {
var chunk;
while ((chunk = doc.read(9007199254740991)) !== null) {
chunks.push(chunk);
}
});
Is it possible to modify the chunk size?

Related

replace one amchart with another

Currently, I have this amchart below.
And I want to create another amchart with the same values. (I just want to replace the graph).
The new graphic is here -> https://www.amcharts.com/demos/line-graph/?theme=material#code
my code Angular:
prepareDataForTemplate(res) {
this.showLineChart = false;
if (res.RETURNCODE == 'OKK00') {
this.lines = [];
this.dataForChart.data.splice(0, this.dataForChart.data.length);
this.dataForChart.date.splice(0, this.dataForChart.date.length);
this.dataForChart.data.push(...res.HISTDEV.VALUE.map(x => x.COURS));
this.dataForChart.date.push(...res.HISTDEV.VALUE.map(x => x.DATE));
this.showLineChart = true;
if (res.HISTDEV.VALUE.length > 0) {
this.yMin = res.HISTDEV.VALUE[0].COURS;
this.yMax = res.HISTDEV.VALUE[0].COURS;
res.HISTDEV.VALUE.map(value => {
if (value.COURS < this.yMin) {
this.yMin = value.COURS;
}
if (value.COURS > this.yMax) {
this.yMax = value.COURS;
}
})
}
this.loadChart();
} else {
}
}
Then, the method loadChart(), it is the graph that I want to change...
loadChart() {
let datePipe = this.datePipe;
let decimalPipe = this.decimalPipe;
let leleuxNumPipe = this.leleuxNumPipe;
this.lineChartReturn = {
tooltip: {
trigger: 'axis',
position: function(pt) {
return [pt[0], '10%'];
},
formatter: function(params) {
return datePipe.transform(params[0].name) + "<br/>" +
params[0].marker + " " +
params[0].seriesName + " <b>" +
leleuxNumPipe.transform(decimalPipe.transform(params[0].value, '1.2-2')) + "</b";
}
},
title: {
left: 'center',
text: '',
},
xAxis: {
type: 'category',
boundaryGap: false,
//show: true,
data: this.dataForChart.date,
axisLabel: {
formatter: function(value, index) {
return datePipe.transform(value);
}
}
},
yAxis: {
type: 'value',
min: this.yMin,
max: this.yMax,
//show: true
axisLabel: {
formatter: function(value, index) {
return leleuxNumPipe.transform(decimalPipe.transform(value, '1.2-2'))
}
}
},
dataZoom: [{
type: 'inside',
start: 0,
end: 100
}, {
start: 0,
end: 10,
handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
handleSize: '80%',
handleStyle: {
color: '#fff',
shadowBlur: 3,
shadowColor: 'rgba(0, 0, 0, 0.6)',
shadowOffsetX: 2,
shadowOffsetY: 2
}
}],
series: [{
name: 'Amount',
type: 'line',
smooth: true,
symbol: 'none',
sampling: 'average',
itemStyle: {
color: 'rgba(255, 152, 0, .6)', // 'rgb(255, 70, 131)'
},
areaStyle: {
color: 'rgba(255, 152, 0, 0.15)',
origin: 'start'
},
lineStyle: {
// width: 1,
color: 'rgba(255, 152, 0, .6)',
},
data: this.dataForChart.data,
}, ]
};
}
In the doc amchart -> https://www.amcharts.com/demos/line-graph/?theme=material#code
I don't understand how to I adapt the code from amcharts with my method loadchart() ?
Sorry, if I ask you a lot
I'm pretty new to amcharts myself, but I'll give it a try.
First, I'm assuming that if you have a chart that you want to replace, you can save a reference to it, that would look something like this:
private chart: am4charts.XYChart;
And when you create your chart for the first time, wherever it is, you can do somthing like this:
this.chart = am4core.createFromConfig(this.lineChartReturn, 'htmlIdReference', am4charts.XYChart);
If your setup looks something like that, then you should be able to just use the dispose function, and then create it again with the new lineChartReturn you generate in loadChart
loadChart() {
if (this.chart) {
this.chart.dispose();
}
// your current code to generate new this.lineChartReturn
// Then just create it again using the createFromConfig
this.chart = am4core.createFromConfig(this.lineChartReturn, 'htmlIdReference', am4charts.XYChart);
}

Changing xaxis label from echarts library

var data = [];
var dataCount = 10;
var startTime = +new Date();
var categories = ['categoryA', 'categoryB', 'categoryC'];
var types = [
{name: 'JS Heap', color: '#7b9ce1'},
{name: 'Documents', color: '#bd6d6c'},
{name: 'Nodes', color: '#75d874'},
{name: 'Listeners', color: '#e0bc78'},
{name: 'GPU Memory', color: '#dc77dc'},
{name: 'GPU', color: '#72b362'}
];
// Generate mock data
echarts.util.each(categories, function (category, index) {
var baseTime = startTime;
for (var i = 0; i < dataCount; i++) {
var typeItem = types[Math.round(Math.random() * (types.length - 1))];
var duration = Math.round(Math.random() * 10000);
data.push({
name: typeItem.name,
value: [
index,
baseTime,
baseTime += duration,
duration
],
itemStyle: {
normal: {
color: typeItem.color
}
}
});
baseTime += Math.round(Math.random() * 2000);
}
});
function renderItem(params, api) {
var categoryIndex = api.value(0);
var start = api.coord([api.value(1), categoryIndex]);
var end = api.coord([api.value(2), categoryIndex]);
var height = api.size([0, 1])[1] * 0.6;
var rectShape = echarts.graphic.clipRectByRect({
x: start[0],
y: start[1] - height / 2,
width: end[0] - start[0],
height: height
}, {
x: params.coordSys.x,
y: params.coordSys.y,
width: params.coordSys.width,
height: params.coordSys.height
});
return rectShape && {
type: 'rect',
shape: rectShape,
style: api.style()
};
}
option = {
tooltip: {
formatter: function (params) {
return params.marker + params.name + ': ' + params.value[3] + ' ms';
}
},
title: {
text: 'Profile',
left: 'center'
},
dataZoom: [{
type: 'slider',
filterMode: 'weakFilter',
showDataShadow: false,
top: 400,
height: 10,
borderColor: 'transparent',
backgroundColor: '#e2e2e2',
handleIcon: 'M10.7,11.9H9.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4h1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7v-1.2h6.6z M13.3,22H6.7v-1.2h6.6z M13.3,19.6H6.7v-1.2h6.6z', // jshint ignore:line
handleSize: 20,
handleStyle: {
shadowBlur: 6,
shadowOffsetX: 1,
shadowOffsetY: 2,
shadowColor: '#aaa'
},
labelFormatter: ''
}, {
type: 'inside',
filterMode: 'weakFilter'
}],
grid: {
height:300
},
xAxis: {
min: startTime,
scale: true,
axisLabel: {
formatter: function (val) {
return Math.max(0, val - startTime) + ' ms';
}
}
},
yAxis: {
data: categories
},
series: [{
type: 'custom',
renderItem: renderItem,
itemStyle: {
normal: {
opacity: 0.8
}
},
encode: {
x: [1, 2],
y: 0
},
data: data
}]
};
Hi, everyone!! I am working on the echarts library, the only thing i want to change data is the axisLabel from Xaxis part.
What i mean is, for example, "2019-11-5, 2019-11-6...."and so on. So, i hope someone can help me out, thank you so much!!!
Hi, everyone!! I am working on the echarts library, the only thing i want to change data is the axisLabel from Xaxis part.
What i mean is, for example, "2019-11-5, 2019-11-6...."and so on. So, i hope someone can help me out, thank you so much!!!
First, create an array of dates like
var dates = ['2019-11-5','2019-10-3','2019-2-2','2019-1-4','2019-12-5'];
then in xAxis -> axisLabel return date
axisLabel: {
formatter: function (val,index) {
return dates[index];
}
}

Simplify JavaScript array variable

I'm looking to simplify this code. Any way to it so? Spring MVC + Apex Charts
var d = /*[[${s0}]]*/ null`; <-- It is sent via the Spring Framework. Basically represents datetime(in millis) at `d[0]`, `d[3]`,... Temperature at `d[1]`, `d[4]`,... and Humidity at `d[2]`, `d[5]`,...
<script type="text/javascript" th:inline="javascript">
var d = /*[[${s0}]]*/ null;
var options = {
chart: {
type: 'area',
height: 300
},
series: [
{
name: 'Temperature',
data: [
[d[0], d[1]],
[d[3], d[4]],
[d[6], d[7]],
[d[9], d[10]],
[d[12], d[13]],
[d[15], d[16]],
[d[18], d[19]],
[d[21], d[22]],
[d[24], d[25]],
[d[27], d[28]],
[d[30], d[31]],
[d[33], d[34]],
[d[36], d[37]],
[d[39], d[40]],
[d[42], d[43]],
[d[45], d[46]],
[d[48], d[49]],
[d[51], d[52]],
[d[54], d[55]],
[d[57], d[58]],
[d[60], d[61]],
[d[63], d[64]],
[d[66], d[67]],
[d[69], d[70]]
]
},
{
name: "Humidity",
data: [
[d[0], d[2]],
[d[3], d[5]],
[d[6], d[8]],
[d[9], d[11]],
[d[12], d[14]],
[d[15], d[17]],
[d[18], d[20]],
[d[21], d[23]],
[d[24], d[26]],
[d[27], d[29]],
[d[30], d[32]],
[d[33], d[35]],
[d[36], d[38]],
[d[39], d[41]],
[d[42], d[44]],
[d[45], d[47]],
[d[48], d[50]],
[d[51], d[53]],
[d[54], d[56]],
[d[57], d[59]],
[d[60], d[62]],
[d[63], d[65]],
[d[66], d[68]],
[d[69], d[71]]
]
}
],
xaxis: {
type: 'datetime'
},
yaxis: [
{
axisTicks: {
show: true
},
axisBorder: {
show: true,
},
title: {
text: "Temperature"
}
}, {
min: 0,
max: 100,
opposite: true,
axisTicks: {
show: true
},
axisBorder: {
show: true,
},
title: {
text: "Humidity"
}
}
],
legend: {
position: 'top',
horizontalAlign: 'center'
},
tooltip: {
x: {
format: 'HH:mm dd/MM/yy'
},
}
}
var chart = new ApexCharts(document.querySelector("#chart0"), options);
chart.render();
</script>
I just need to simplify sending data via d[0], d[1] etc. Is there any kind of loop or anything else I can use?
You could take a function which takes the data and a pattern for the wanted elements and an offset for increment for the next row.
function mapByPattern(data, pattern, offset) {
var result = [], i = 0;
while (i < data.length) {
result.push(pattern.map(j => data[i + j]));
i += offset;
}
return result;
}
var data = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
result = { series: [
{ name: 'Temperature', data: mapByPattern(data, [0, 1], 3) },
{ name: "Humidity", data: mapByPattern(data, [0, 2], 3) }
]};
console.log(result);
Thank You, Nina. Code code didn't work exactly as i wanted but was so helpful to fix my own. Thanks alot! Here's some fixed code :)
var data = /*[[${s0}]]*/ null;
function mapByPattern(data, pattern, offset) {
var result = [], i = 0;
while (i < data.length) {
result.push(pattern.map(j => data[i + j]));
i += offset;
}
return result;
}
var options = {
chart: {
type: 'area',
height: 300
},
series: [
{
name: 'Temperature',
data: mapByPattern(data, [0, 1], 3)
},
{
name: "Humidity",
data: mapByPattern(data, [0, 2], 3)
}
],
xaxis: {
type: 'datetime'
},
yaxis: [
{
axisTicks: {
show: true
},
axisBorder: {
show: true,
},
title: {
text: "Temperature"
}
}, {
min: 0,
max: 100,
opposite: true,
axisTicks: {
show: true
},
axisBorder: {
show: true,
},
title: {
text: "Humidity"
}
}
],
legend: {
position: 'top',
horizontalAlign: 'center'
},
tooltip: {
x: {
format: 'HH:mm dd/MM/yy'
},
}
}
var chart = new ApexCharts(document.querySelector("#chart0"), options);
chart.render();

High Charts windrose from API data (JSON)

I'm quite new here (and to web development in general), so please forgive any misuses that I perpetuate... I'm trying to create a basic windrose plot with data returned (in JSON) from the MesoWest Mesonet API service. I'm using HighCharts (or attempting to), and cannot quite get it to work. Perhaps this is due to my methodology of obtaining the data from the API itself as I'm a complete amateur in this regard. The following is the Javascript code, followed by the HTML for the page. Could someone please take a look and let me know what I've done wrong? Nothing displays on the page when I attempt to load it. In addition, if you're curious as to the specifics of an API call for MesoWest, like the one I've employed here, please see http://mesowest.org/api/docs/
The .js script:
var windrose = {
divname: "windrosediv",
tkn: "eecfc0259e2946a68f41080021724419",
load:function()
{
console.log('loading')
if (!window.jQuery) {
var script = document.createElement("script");
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js';
script.type = 'text/javascript';
document.getElementByTagName("head")[0].appendChild(script);
setTimeout(pollJQuery, 100)
return
}
this.div = $("#"+this.divname);
this.request('WBB');
},
pollJQuery:function()
{
if (!window.jQuery) {
setTimeout(pollJQuery,100);
} else {
load();
}
},
request:function(stn){
console.log("making a request")
$.getJSON(http://api.mesowest.net/v2/stations/nearesttime?callback=?',
{
stid:stn,
within:1440,
units:'english',
token:windrose.tkn
}, this.receive);
},
receive:function (data)
{
console.log(data,windrose);
stn = data.STATION[0]
dat = stn.OBSERVATIONS
spd += Math.round(dat.wind_speed_value_1.value)
dir += dat.wind_direction_value_1.value
windDataJSON = [];
for (i = 0; i < dir.length; i++) {
windDataJSON.push([ dir[i], spd[i]
]);
},
}
$(function () {
var categories = ['0', '45', '90', '135', '180', '225', '270', '315'];
$('#container').highcharts({
series: [{
data: windDataJSON
}],
chart: {
polar: true,
type: 'column'
},
title: {
text: 'Wind Rose'
},
pane: {
size: '85%'
},
legend: {
align: 'right',
verticalAlign: 'top',
y: 100,
layout: 'vertical'
},
xAxis: {
min: 0,
max: 360,
type: "",
tickInterval: 22.5,
tickmarkPlacement: 'on',
labels: {
formatter: function () {
return categories[this.value / 22.5] + '°';
}
}
},
yAxis: {
min: 0,
endOnTick: false,
showLastLabel: true,
title: {
text: 'Frequency (%)'
},
labels: {
formatter: function () {
return this.value + '%';
}
},
reversedStacks: false
},
tooltip: {
valueSuffix: '%'
},
plotOptions: {
series: {
stacking: 'normal',
shadow: false,
groupPadding: 0,
pointPlacement: 'on'
}
}
});
});
And the HTML:
<!DOCTYPE html>
<html>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/highcharts-more.js"></script>
<script src="https://code.highcharts.com/modules/data.js">`enter code </script>
<script src="https://code.highcharts.com/modules/exporting.js"> </script>
<div id="container" style="min-width: 420px; max-width: 600px; height: 400px; margin: 0 auto"></div>
<p class="ex">
<script type="text/javascript" src="http://home.chpc.utah.edu/~u0675379/apiDemos/windTest.js"></script>
</p>
</html>
I appreciate any guidance in this regard, thanks!!!
-Will
#W.Howard, I think the problem here is how you are treating and preparing the JSON response from the API. Consider the following JavaScript to retrieve and parse out the data:
/*
* Helper function
* scalarMultiply(array, scalar)
*/
function scalarMultiply(arr, scalar) {
for (var i = 0; i < arr.length; i++) {
arr[i] = arr[i] * scalar;
}
return arr;
}
/*
* getQuery(station, api_token)
*/
function getQuery(station, mins, api_token) {
$.getJSON('http://api.mesowest.net/v2/stations/timeseries?callback=?', {
/* Specify the request parameters here */
stid: station,
recent: mins, /* How many mins you want */
obtimezone: "local",
vars: "wind_speed,wind_direction,wind_gust",
jsonformat: 2, /* for diagnostics */
token: api_token
},
function(data) {
try {
windSpeed = data.STATION[0].OBSERVATIONS.wind_speed_set_1;
windDir = data.STATION[0].OBSERVATIONS.wind_direction_set_1;
windGust = data.STATION[0].OBSERVATIONS.wind_gust_set_1;
} catch (err) {
console.log("Data is invalid. Check your API query");
console.log(this.url);
exit();
}
/* Convert from knots to mph */
windSpeed = scalarMultiply(windSpeed, 1.15078);
//windGust = scalarMultiply(windGust, 1.15078);
/* Create and populate array for plotting */
windData = [];
for (i = 0; i < windSpeed.length; i++) {
windData.push([windDir[i], windSpeed[i]]);
}
/* Debug */
// console.log(windData);
console.log(this.url);
plotWindRose(windData, mins);
})
};
What we had now is an 2D array with wind direction and wind speed that we can pass to the plotting function. Below is the updated plotting function:
/*
* Plot the wind rose
* plotWindRose([direction, speed])
*/
function plotWindRose(windData, mins) {
/*
* Note:
* Because of the nature of the data we will accept the HighCharts Error #15.
* --> Highcharts Error #15 (Highcharts expects data to be sorted).
* This only results in a performance issue.
*/
var categories = ["0", "45", "90", "135", "180", "225", "270", "315"];
$('#wind-rose').highcharts({
series: [{
name: "Wind Speed",
color: '#cc3000',
data: windData
}],
chart: {
type: 'column',
polar: true
},
title: {
text: 'Wind Direction vs. Frequency (Last ' + mins/60. + ' hours)'
},
pane: {
size: '90%',
},
legend: {
align: 'right',
verticalAlign: 'top',
y: 100,
text: "Wind Direction"
},
xAxis: {
min: 0,
max: 360,
type: "",
tickInterval: 45,
tickmarkPlacement: 'on',
labels: {
formatter: function() {
return categories[this.value / 45] + '\u00B0';
}
}
},
yAxis: {
min: 0,
endOnTick: false,
showLastLabel: true,
title: {
text: 'Frequency (%)'
},
labels: {
formatter: function() {
return this.value + '%';
}
},
reversedStacks: false
},
tooltip: {
valueSuffix: '%'
},
plotOptions: {
series: {
stacking: 'normal',
shadow: false,
groupPadding: 20,
pointPlacement: 'on'
}
}
});
}
You can see it all here at https://gist.github.com/adamabernathy/eda63f14d79090ab1ea411a8df1e246e . Best of luck!

running a "background task" in javascript

Is it possible, in Javascript, to run a function in background ?
I am generating a pdf with pdfmake tool in an angularJS app, but the pdf generation is quite long (3-4 seconds) and during this time, the ui freeze completely.
I would like to run a background task and force the pdf download without freezing the user ui, is it possible ?
Here how I am running pdfmake (pdfmake and _ are custom factories):
'use strict';
angular.module('App')
.service('CatalogPdfService', ['pdfmake', '_', '$q', '$filter',
function (pdfmake, _, $q, $filter) {
var $translate = $filter('translate');
var listDate = new Date();
return {
download: download
};
function download(data) {
listDate = _.first(data).publishedOn;
console.log('start download');
var deferred = $q.defer();
var filename = $translate('APP.EXPORT.pdf.catalog.title', {date: $filter('amDateFormat')(listDate, 'DDMMYYYY')}) + '.pdf';
create(data).download(filename, function () {
console.log('end download');
deferred.resolve();
});
return deferred.promise;
}
function create(data) {
// group data by category
var dataByCategory = _.groupBy(data, function (d) {
return d.category;
});
// group categories data by subcategory
_.forEach(dataByCategory, function (d, i) {
dataByCategory[i] = _.groupBy(d, function (d) {
return d.subcategory;
});
});
var content = {
table: {
headerRows: 1,
widths: ['*', 20, 10, 20, 20, 20, 20, 40, 20, 30],
body: [
[
{text: $translate('APP.EXPORT.pdf.catalog.header.article') , style: 'headings', alignment: 'left'},
{text: $translate('APP.EXPORT.pdf.catalog.header.mine') , style: 'headings'},
{text: $translate('APP.EXPORT.pdf.catalog.header.rank') , style: 'headings'},
{text: $translate('APP.EXPORT.pdf.catalog.header.origin') , style: 'headings'},
{text: $translate('APP.EXPORT.pdf.catalog.header.transporter') , style: 'headings'},
{text: $translate('APP.EXPORT.pdf.catalog.header.culture') , style: 'headings'},
{text: $translate('APP.EXPORT.pdf.catalog.header.label') , style: 'headings'},
{text: $translate('APP.EXPORT.pdf.catalog.header.unit') , style: 'headings'},
{text: $translate('APP.EXPORT.pdf.catalog.header.packing') , style: 'headings'},
{text: $translate('APP.EXPORT.pdf.catalog.header.price') , style: 'headings'}
]
]
},
layout: {
hLineWidth: function (i) {
return (i == 0) ? 0 : 1;
},
vLineWidth: function (i) {
return 0;
},
hLineColor: function (i, node) {
return '#ccc';
}
}
};
_.forEach(dataByCategory, function (data, category) {
content.table.body = content.table.body.concat(renderCategory(category, data));
});
var dd = {};
dd.content = renderHeader().concat(content);
dd.header = function (currentPage, pageCount) {
return {
text: $translate('APP.EXPORT.pdf.catalog.pagecount', {start: currentPage.toString(), end: pageCount.toString()}),
alignment: 'right',
color: '#666',
margin: [0, 20, 40, 0]
};
};
dd.styles = {
title: {
fontSize: 15,
bold: true
},
headings: {
italics: true,
alignment: 'center'
},
flag: {
alignment: 'center',
italics: true,
color: '#666'
},
category: {
bold: true,
fontSize: 12,
margin: [0, 10, 0, 0] // Left, Top, Right, Bottom
},
subcategory: {
bold: true,
fontSize: 10,
margin: [0, 7, 0, 5] // Left, Top, Right, Bottom
}
};
dd.defaultStyle = {
fontSize: 8
};
return pdfmake.createPdf(dd);
}
function renderHeader() {
return [
{image: logo(), height:40, width: 86},
{
margin: [0, 10, 0, 20],
table: {
widths: [100, 100, 100, '*'],
body: [
[
{text: $translate('APP.COMMON.address', {char: '\n'})},
{text: '\n' + $translate('APP.COMMON.phone')},
{text: '\n' + $translate('APP.COMMON.fax')},
{text: '\n' + $translate('APP.EXPORT.pdf.catalog.listno', {date: $filter('amDateFormat')(listDate, 'DD/MM/YYYY')}) , alignment: 'right'}
]
]
},
layout: {
hLineWidth: function (i) {
return (i == 0) ? 0 : 1;
},
vLineWidth: function (i) {
return 0;
}
}
}];
}
function renderCategory(name, data) {
var category = [
[
{text: name, style: 'category', colspan: 10},
'', '', '', '', '', '', '', '', ''
]
];
_.forEach(data, function (data, name) {
category = category.concat(renderSubcategory(name, data));
});
return category;
}
function renderSubcategory(name, data) {
var subcategory = [
[
{text: name, style: 'subcategory', colspan: 10},
'', '', '', '', '', '', '', '', ''
]
];
_.forEach(data, function (product) {
subcategory.push(renderProduct(product));
});
return subcategory;
}
function renderProduct(product) {
return [
product.name,
{
text: (product.isInPrivateList ? 'Oui' : ''),
style: 'flag'
},
{
text: (null === product.rank ? '' : String(product.rank)),
style: 'flag'
},
{
text: (product.origin || ''),
style: 'flag'
},
{
text: (product.transporter || ''),
style: 'flag'
},
{
text: (product.label || ''),
style: 'flag'
},
{
text: (product.culture || ''),
style: 'flag'
},
{
text: product.unit,
margin: [0, 0, 5, 0],
italics: true,
alignment: 'right'
},
{
text: (product.quantity || '1'),
italics: true,
fillColor: '#eee',
alignment: 'center'
},
{
text: product.unitPrice,
margin: [0, 0, 5, 0],
italics: true,
fillColor: '#eee',
alignment: 'right'
}
];
}
function logo() {
return 'data:image/jpeg;base64,blabla bigbase64 string'
}
}]);
You could use a Web Worker to generate the PDF. But you should be aware of some restrictions when using them. Here is a good reference.
I created a factory in Angular for doing work on a worker thread. Something like this:
/*
Here's an example on how to get this sack of moldering spuds to do something:
var myWorker = new MyWorker({ fn: function() {
this.onmessage = function(args) {
setTimeout(function() {
this.postMessage('Got args: ' + args.data);
}, 20000);
};
} });
myWorker.do('Test').then(function(message) {
alert(message);
});
*/
'use strict';
angular.module('myApp')
.factory('MyWorker', function($q) {
var _worker;
var MyWorker = function(settings) {
_init(settings);
};
MyWorker.prototype.do = function(args) {
var deferred = $q.defer();
_worker.onmessage = function(message) {
deferred.resolve(message.data);
};
//Fire up the blades.
if (args)
_worker.postMessage(args);
else
_worker.postMessage();
return deferred.promise;
};
MyWorker.prototype.destroy = function() {
_worker.terminate();
};
function _init(settings) {
if (settings.script)
_worker = new Worker(settings.script);
//Need to make this IE (10+) friendly.
else if (settings.fn) {
var blobUrl = window.URL.createObjectURL(new Blob(
['(', settings.fn.toString(), ')()'],
{ type: 'application/javascript' }
));
_worker = new Worker(blobUrl);
}
};
return MyWorker;
});
This will give you a rough idea about how it can be implemented in AngularJS, but seriously take it with a grain of salt.

Categories

Resources