forked from jeroenbaas/phantomjs-google-charts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
google-convert.js
428 lines (372 loc) · 11.7 KB
/
google-convert.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
/**
* @license Highcharts JS v3.0.1 (2012-11-02)
*
* (c) 20013-2014
*
* Author: Jeroen Baas
* Based on: https://github.com/highslide-software/highcharts.com/blob/master/exporting-server/phantomjs/highcharts-convert.js
* Original HighCharts-convert.js:
* Author: Gert Vaartjes
* License: www.highcharts.com/license
* version: 2.0.1
*/
/*jslint white: true */
/*global window, require, phantom, console, $, document, Image, Highcharts, clearTimeout, clearInterval, options, cb */
(function () {
"use strict";
var config = {
/* define locations of mandatory javascript files */
JQUERY: 'jquery.1.9.1.min.js',
TIMEOUT: 8000 /* 8 seconds timout for loading the chart. google may need time for plotting locations (marker map) */
},
mapCLArguments,
render,
startServer = false,
args,
pick,
SVG_DOCTYPE = '<?xml version=\"1.0" standalone=\"no\"?><!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">',
dpiCorrection = 1.4,
system = require('system'),
fs = require('fs');
pick = function () {
var args = arguments, i, arg, length = args.length;
for (i = 0; i < length; i += 1) {
arg = args[i];
if (arg !== undefined && arg !== null && arg !== 'null' && arg != '0') {
return arg;
}
}
};
mapCLArguments = function () {
var map = {},
i,
key;
if (system.args.length < 1) {
console.log('Commandline Usage: google-convert.js -infile URL -outfile filename -scale 2.5 -width 300 -constr Chart -callback callback.js');
console.log(', or run PhantomJS as server: google-convert.js -host 127.0.0.1 -port 1234');
}
for (i = 0; i < system.args.length; i += 1) {
if (system.args[i].charAt(0) === '-') {
key = system.args[i].substr(1, i.length);
if (key === 'infile' || key === 'callback' || key === 'dataoptions' || key === 'globaloptions' || key === 'customcode') {
// get string from file
try {
map[key] = fs.read(system.args[i + 1]);
} catch (e) {
console.log('Error: cannot find file, ' + system.args[i + 1]);
phantom.exit();
}
} else {
map[key] = system.args[i + 1];
}
}
}
return map;
};
render = function (params, runsAsServer, exitCallback) {
var page = require('webpage').create(),
messages = {},
scaleAndClipPage,
loadChart,
input,
constr,
callback,
width,
output,
outputExtension,
svgInput,
svg,
svgFile,
timer,
renderSVG,
convert,
exit,
interval;
messages.imagesLoaded = 'Highcharts.images.loaded';
messages.optionsParsed = 'Highcharts.options.parsed';
messages.callbackParsed = 'Highcharts.cb.parsed';
messages.ischartready='Google.chart.ready';
window.imagesLoaded = true;//false;
window.optionsParsed = false;
window.callbackParsed = false;
window.ischartready=false;
page.onConsoleMessage = function (msg) {
//console.log(msg);
/*
* Ugly hack, but only way to get messages out of the 'page.evaluate()'
* sandbox. If any, please contribute with improvements on this!
*/
if (msg === messages.ischartready) {
window.ischartready = true;
}
if (msg === messages.imagesLoaded) {
window.imagesLoaded = true;
}
/* more ugly hacks, to check options or callback are properly parsed */
if (msg === messages.optionsParsed) {
window.optionsParsed = true;
}
if (msg === messages.callbackParsed) {
window.callbackParsed = true;
}
};
page.onAlert = function (msg) {
console.log(msg);
};
/* scale and clip the page */
scaleAndClipPage = function (svg) {
/* param: svg: The scg configuration object
*/
var zoom = 1,
pageWidth = pick(params.width, svg.width),
clipwidth,
clipheight;
if (parseInt(pageWidth, 10) == pageWidth) {
zoom = pageWidth / svg.width;
}
/* set this line when scale factor has a higher precedence
scale has precedence : page.zoomFactor = params.scale ? zoom * params.scale : zoom;*/
/* params.width has a higher precedence over scaling, to not break backover compatibility */
page.zoomFactor = params.scale && params.width == undefined ? zoom * params.scale : zoom;
clipwidth = svg.width * page.zoomFactor;
clipheight = svg.height * page.zoomFactor;
/* define the clip-rectangle */
/* ignored for PDF, see https://github.com/ariya/phantomjs/issues/10465 */
page.clipRect = {
top: 0,
left: 0,
width: clipwidth,
height: clipheight
};
/* for pdf we need a bit more paperspace in some cases for example (w:600,h:400), I don't know why.*/
if (outputExtension === 'pdf') {
// changed to a multiplication with 1.333 to correct systems dpi setting
clipwidth = clipwidth * dpiCorrection;
clipheight = clipheight * dpiCorrection;
// redefine the viewport
page.viewportSize = { width: clipwidth, height: clipheight};
// make the paper a bit larger than the viewport
page.paperSize = { width: clipwidth + 2 , height: clipheight + 2 };
}
};
exit = function (result) {
if (runsAsServer) {
//Calling page.close(), may stop the increasing heap allocation
page.close();
}
exitCallback(result);
};
convert = function (svg) {
var base64;
scaleAndClipPage(svg);
if (outputExtension === 'pdf' || !runsAsServer) {
page.render(output);
exit(output);
} else {
base64 = page.renderBase64(outputExtension);
exit(base64);
}
};
renderSVG = function (svg) {
// From this point we have loaded/or created a SVG
try {
if (outputExtension.toLowerCase() === 'svg') {
// output svg
svg = svg.html.replace(/<svg /, '<svg xmlns:xlink="http://www.w3.org/1999/xlink" ').replace(/ href=/g, ' xlink:href=').replace(/<\/svg>.*?$/, '</svg>');
// add xml doc type
svg = SVG_DOCTYPE + svg;
if (!runsAsServer) {
// write the file
svgFile = fs.open(output, "w");
svgFile.write(svg);
svgFile.close();
exit(output);
} else {
// return the svg as a string
exit(svg);
}
} else {
// output binary images or pdf
if (!window.ischartready) {
// render with interval, waiting for all images loaded
interval = window.setInterval(function () {
console.log('waiting');
if (window.ischartready) {
clearTimeout(timer);
clearInterval(interval);
convert(svg);
}
}, 50);
// we have a 3 second timeframe..
timer = window.setTimeout(function () {
clearInterval(interval);
exitCallback('ERROR: While rendering, there\'s is a timeout reached');
}, config.TIMEOUT);
} else {
// images are loaded, render rightaway
convert(svg);
}
}
} catch (e) {
console.log('ERROR: While rendering, ' + e);
}
};
loadChart = function (input, outputFormat, messages) {
var nodeIter, nodes, elem, opacity, counter, svgElem;
document.body.style.margin = '0px';
document.body.innerHTML = input;
function loadingImage() {
console.log('Loading image ' + counter);
counter -= 1;
if (counter < 1) {
console.log(messages.imagesLoaded);
}
}
function loadImages() {
var images = document.getElementsByTagName('image'), i, img;
if (images.length > 0) {
counter = images.length;
for (i = 0; i < images.length; i += 1) {
img = new Image();
img.onload = loadingImage;
/* force loading of images by setting the src attr.*/
img.src = images[i].href.baseVal;
}
} else {
// no images set property to:imagesLoaded = true
console.log(messages.imagesLoaded);
}
}
if (outputFormat === 'jpeg') {
document.body.style.backgroundColor = 'white';
}
nodes = document.querySelectorAll('*[stroke-opacity]');
for (nodeIter = 0; nodeIter < nodes.length; nodeIter += 1) {
elem = nodes[nodeIter];
opacity = elem.getAttribute('stroke-opacity');
elem.removeAttribute('stroke-opacity');
elem.setAttribute('opacity', opacity);
}
// ensure all image are loaded
loadImages();
svgElem = document.getElementsByTagName('svg')[0];
return {
html: document.body.innerHTML,
width: svgElem.getAttribute("width"),
height: svgElem.getAttribute("height")
};
};
if (params.length < 1) {
// TODO: log when using as server
exit("Error: Insuficient parameters");
} else {
input = params.infile;
output = pick(params.outfile, "chart.png");
constr = pick(params.constr, 'Chart');
callback = params.callback;
width = params.width;
if (input === undefined || input.length === 0) {
exit('Error: Insuficient or wrong parameters for rendering');
}
outputExtension = output.split('.').pop();
/* Decide if we have to generate a svg first before rendering */
svgInput = input.substring(0, 4).toLowerCase() === "<svg" ? true : false;
page.open('gpage.html', function (status) {
var svg,
globalOptions = params.globaloptions,
dataOptions = params.dataoptions,
customCode = 'function customCode(options) {\n' + params.customcode + '}\n';
if (svgInput) {
//render page directly from svg file
svg = page.evaluate(loadChart, input, outputExtension, messages);
page.viewportSize = { width: svg.width, height: svg.height };
renderSVG(svg);
} else {
// We have a js file, let highcharts create the chart first and grab the svg
// load necessary libraries
page.injectJs(config.JQUERY);
page.evaluate(function(input) {
// dynamic script insertion
function loadScript(varStr, codeStr) {
var $script = $('<script>').attr('type', 'text/javascript');
$script.html('var ' + varStr + ' = ' + codeStr);
document.getElementsByTagName("head")[0].appendChild($script[0]);
if (window[varStr] !== undefined) {
console.log('Google.' + varStr + '.parsed');
}
}
function chartready() {
console.log('Google.chart.ready');
}
loadScript('settings',input);
if (settings.width) {
$('#chart_div').width(settings.width);
} else {
$('#chart_div').width(400);
}
if (settings.height) {
$('#chart_div').height(settings.width);
} else {
$('#chart_div').height(400);
}
settings.containerId='chart_div';
var chart = new google.visualization.ChartWrapper(settings);
chart.draw();
google.visualization.events.addListener(chart, 'ready', chartready);
},args.infile);
var svg=page.evaluate(function() {
return {
html: $('#chart_div svg').parent().html(),
width: $('#chart_div').width(),
height: $('#chart_div').height(),//chart.chartHeight
};
});
renderSVG(svg);
}
});
}
};
startServer = function (host, port) {
var server = require('webserver').create(),
service = server.listen(host + ':' + port,
function (request, response) {
var jsonStr = request.post,
params,
msg;
try {
params = JSON.parse(jsonStr);
if (params.status) {
// for server health validation
response.statusCode = 200;
response.write('OK');
response.close();
} else {
render(params, true, function (result) {
// TODO: set response headers?
response.statusCode = 200;
response.write(result);
response.close();
});
}
} catch (e) {
msg = "Failed rendering: \n" + e;
response.statusCode = 500;
response.setHeader('Content-Type', 'text/plain');
response.setHeader('Content-Length', msg.length);
response.write(msg);
response.close();
}
});
console.log("OK, PhantomJS is ready.");
};
args = mapCLArguments();
if (args.port !== undefined) {
startServer(args.host, args.port);
} else {
// presume commandline usage
render(args, false, function (msg) {
console.log(msg);
phantom.exit();
});
}
}());