forked from eKoopmans/html2pdf.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
worker.js
454 lines (387 loc) · 14.7 KB
/
worker.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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
import jsPDF from 'jspdf';
import html2canvas from 'html2canvas';
import { objType, createElement, cloneNode, toPx } from './utils.js';
/* ----- CONSTRUCTOR ----- */
var Worker = function Worker(opt) {
// Create the root parent for the proto chain, and the starting Worker.
var root = Object.assign(Worker.convert(Promise.resolve()),
JSON.parse(JSON.stringify(Worker.template)));
var self = Worker.convert(Promise.resolve(), root);
// Set progress, optional settings, and return.
self = self.setProgress(1, Worker, 1, [Worker]);
self = self.set(opt);
return self;
};
// Boilerplate for subclassing Promise.
Worker.prototype = Object.create(Promise.prototype);
Worker.prototype.constructor = Worker;
// Converts/casts promises into Workers.
Worker.convert = function convert(promise, inherit) {
// Uses prototypal inheritance to receive changes made to ancestors' properties.
promise.__proto__ = inherit || Worker.prototype;
return promise;
};
Worker.template = {
prop: {
src: null,
canvas: null,
img: null,
pdf: null,
pageSize: null
},
progress: {
val: 0,
state: null,
n: 0,
stack: []
},
opt: {
filename: 'file.pdf',
margin: [0,0,0,0],
image: { type: 'jpeg', quality: 0.95 },
enableLinks: true,
html2canvas: {},
jsPDF: {}
}
};
/* ----- FROM / TO ----- */
Worker.prototype.from = function from(src, type) {
function getType(src) {
switch (objType(src)) {
case 'string': return 'string';
case 'element': return src.nodeName.toLowerCase === 'canvas' ? 'canvas' : 'element';
default: return 'unknown';
}
}
return this.then(function from_main() {
type = type || getType(src);
switch (type) {
case 'string': return this.set({ src: createElement('div', {innerHTML: src}) });
case 'element': return this.set({ src: src });
case 'canvas': return this.set({ canvas: src });
case 'img': return this.set({ img: src });
default: return this.error('Unknown source type.');
}
});
};
Worker.prototype.to = function to(target) {
// Route the 'to' request to the appropriate method.
switch (target) {
case 'canvas':
return this.toCanvas();
case 'img':
return this.toImg();
case 'pdf':
return this.toPdf();
default:
return this.error('Invalid target.');
}
};
Worker.prototype.toCanvas = function toCanvas() {
// Set up function prerequisites.
var prereqs = [
function checkSrc() { return this.prop.src || this.error('Cannot duplicate - no source HTML.'); },
function checkPageSize() { return this.prop.pageSize || this.setPageSize(); }
];
// Fulfill prereqs then create the canvas.
return this.thenList(prereqs).then(function toCanvas_main() {
// Handle old-fashioned 'onrendered' argument.
var options = Object.assign({}, this.opt.html2canvas);
delete options.onrendered;
// Alter html2canvas options for reflow behaviour.
var src = this.prop.src;
var ignoreElements_orig = options.ignoreElements || function () {};
options.ignoreElements = function (el) {
// List of metadata tags: https://www.w3schools.com/html/html_head.asp
var metaTags = ['HEAD', 'TITLE', 'BASE', 'LINK', 'META', 'SCRIPT', 'STYLE'];
var toClone = metaTags.indexOf(el.tagName) !== -1 || el.contains(src) || src.contains(el);
return !toClone || ignoreElements_orig(el);
}
options.windowWidth = this.prop.pageSize.inner.px.width;
options.width = options.windowWidth;
return html2canvas(src, options);
}).then(function toCanvas_post(canvas) {
// Handle old-fashioned 'onrendered' argument.
var onRendered = this.opt.html2canvas.onrendered || function () {};
onRendered(canvas);
this.prop.canvas = canvas;
});
};
Worker.prototype.toImg = function toImg() {
// Set up function prerequisites.
var prereqs = [
function checkCanvas() { return this.prop.canvas || this.toCanvas(); }
];
// Fulfill prereqs then create the image.
return this.thenList(prereqs).then(function toImg_main() {
var imgData = this.prop.canvas.toDataURL('image/' + this.opt.image.type, this.opt.image.quality);
this.prop.img = document.createElement('img');
this.prop.img.src = imgData;
});
};
Worker.prototype.toPdf = function toPdf() {
// Set up function prerequisites.
var prereqs = [
function checkCanvas() { return this.prop.canvas || this.toCanvas(); }
];
// Fulfill prereqs then create the image.
return this.thenList(prereqs).then(function toPdf_main() {
// Create local copies of frequently used properties.
var canvas = this.prop.canvas;
var opt = this.opt;
// Calculate the number of pages.
var ctx = canvas.getContext('2d');
var pxFullHeight = canvas.height;
var pxPageHeight = Math.floor(canvas.width * this.prop.pageSize.inner.ratio);
var nPages = Math.ceil(pxFullHeight / pxPageHeight);
// Define pageHeight separately so it can be trimmed on the final page.
var pageHeight = this.prop.pageSize.inner.height;
// Create a one-page canvas to split up the full image.
var pageCanvas = document.createElement('canvas');
var pageCtx = pageCanvas.getContext('2d');
pageCanvas.width = canvas.width;
pageCanvas.height = pxPageHeight;
// Initialize the PDF.
this.prop.pdf = this.prop.pdf || new jsPDF(opt.jsPDF);
for (var page=0; page<nPages; page++) {
// Trim the final page to reduce file size.
if (page === nPages-1 && pxFullHeight % pxPageHeight !== 0) {
pageCanvas.height = pxFullHeight % pxPageHeight;
pageHeight = pageCanvas.height * this.prop.pageSize.inner.width / pageCanvas.width;
}
// Display the page.
var w = pageCanvas.width;
var h = pageCanvas.height;
pageCtx.fillStyle = 'white';
pageCtx.fillRect(0, 0, w, h);
pageCtx.drawImage(canvas, 0, page*pxPageHeight, w, h, 0, 0, w, h);
// Add the page to the PDF.
if (page) this.prop.pdf.addPage();
var imgData = pageCanvas.toDataURL('image/' + opt.image.type, opt.image.quality);
this.prop.pdf.addImage(imgData, opt.image.type, opt.margin[1], opt.margin[0],
this.prop.pageSize.inner.width, pageHeight);
}
});
};
/* ----- OUTPUT / SAVE ----- */
Worker.prototype.output = function output(type, options, src) {
// Redirect requests to the correct function (outputPdf / outputImg).
src = src || 'pdf';
if (src.toLowerCase() === 'img' || src.toLowerCase() === 'image') {
return this.outputImg(type, options);
} else {
return this.outputPdf(type, options);
}
};
Worker.prototype.outputPdf = function outputPdf(type, options) {
// Set up function prerequisites.
var prereqs = [
function checkPdf() { return this.prop.pdf || this.toPdf(); }
];
// Fulfill prereqs then perform the appropriate output.
return this.thenList(prereqs).then(function outputPdf_main() {
/* Currently implemented output types:
* https://rawgit.com/MrRio/jsPDF/master/docs/jspdf.js.html#line992
* save(options), arraybuffer, blob, bloburi/bloburl,
* datauristring/dataurlstring, dataurlnewwindow, datauri/dataurl
*/
return this.prop.pdf.output(type, options);
});
};
Worker.prototype.outputImg = function outputImg(type, options) {
// Set up function prerequisites.
var prereqs = [
function checkImg() { return this.prop.img || this.toImg(); }
];
// Fulfill prereqs then perform the appropriate output.
return this.thenList(prereqs).then(function outputImg_main() {
switch (type) {
case undefined:
case 'img':
return this.prop.img;
case 'datauristring':
case 'dataurlstring':
return this.prop.img.src;
case 'datauri':
case 'dataurl':
return document.location.href = this.prop.img.src;
default:
throw 'Image output type "' + type + '" is not supported.';
}
});
};
Worker.prototype.save = function save(filename) {
// Set up function prerequisites.
var prereqs = [
function checkPdf() { return this.prop.pdf || this.toPdf(); }
];
// Fulfill prereqs, update the filename (if provided), and save the PDF.
return this.thenList(prereqs).set(
filename ? { filename: filename } : null
).then(function save_main() {
this.prop.pdf.save(this.opt.filename);
});
};
/* ----- SET / GET ----- */
Worker.prototype.set = function set(opt) {
// TODO: Implement ordered pairs?
// Silently ignore invalid or empty input.
if (objType(opt) !== 'object') {
return this;
}
// Build an array of setter functions to queue.
var fns = Object.keys(opt || {}).map(function (key) {
if (key in Worker.template.prop) {
// Set pre-defined properties.
return function set_prop() { this.prop[key] = opt[key]; }
} else {
switch (key) {
case 'margin':
return this.setMargin.bind(this, opt.margin);
case 'jsPDF':
return function set_jsPDF() { this.opt.jsPDF = opt.jsPDF; return this.setPageSize(); }
case 'pageSize':
return this.setPageSize.bind(this, opt.pageSize);
default:
// Set any other properties in opt.
return function set_opt() { this.opt[key] = opt[key] };
}
}
}, this);
// Set properties within the promise chain.
return this.then(function set_main() {
return this.thenList(fns);
});
};
Worker.prototype.get = function get(key, cbk) {
return this.then(function get_main() {
// Fetch the requested property, either as a predefined prop or in opt.
var val = (key in Worker.template.prop) ? this.prop[key] : this.opt[key];
return cbk ? cbk(val) : val;
});
};
Worker.prototype.setMargin = function setMargin(margin) {
return this.then(function setMargin_main() {
// Parse the margin property: [top, left, bottom, right].
switch (objType(margin)) {
case 'number':
margin = [margin, margin, margin, margin];
case 'array':
if (margin.length === 2) {
margin = [margin[0], margin[1], margin[0], margin[1]];
}
if (margin.length === 4) {
break;
}
default:
return this.error('Invalid margin array.');
}
// Set the margin property, then update pageSize.
this.opt.margin = margin;
}).then(this.setPageSize);
}
Worker.prototype.setPageSize = function setPageSize(pageSize) {
return this.then(function setPageSize_main() {
// Retrieve page-size based on jsPDF settings, if not explicitly provided.
pageSize = pageSize || jsPDF.getPageSize(this.opt.jsPDF);
// Add 'inner' field if not present.
if (!pageSize.hasOwnProperty('inner')) {
pageSize.inner = {
width: pageSize.width - this.opt.margin[1] - this.opt.margin[3],
height: pageSize.height - this.opt.margin[0] - this.opt.margin[2]
};
pageSize.inner.px = {
width: toPx(pageSize.inner.width, pageSize.k),
height: toPx(pageSize.inner.height, pageSize.k)
};
pageSize.inner.ratio = pageSize.inner.height / pageSize.inner.width;
}
// Attach pageSize to this.
this.prop.pageSize = pageSize;
});
}
Worker.prototype.setProgress = function setProgress(val, state, n, stack) {
// Immediately update all progress values.
if (val != null) this.progress.val = val;
if (state != null) this.progress.state = state;
if (n != null) this.progress.n = n;
if (stack != null) this.progress.stack = stack;
this.progress.ratio = this.progress.val / this.progress.state;
// Return this for command chaining.
return this;
};
Worker.prototype.updateProgress = function updateProgress(val, state, n, stack) {
// Immediately update all progress values, using setProgress.
return this.setProgress(
val ? this.progress.val + val : null,
state ? state : null,
n ? this.progress.n + n : null,
stack ? this.progress.stack.concat(stack) : null
);
};
/* ----- PROMISE MAPPING ----- */
Worker.prototype.then = function then(onFulfilled, onRejected) {
// Wrap `this` for encapsulation.
var self = this;
return this.thenCore(onFulfilled, onRejected, function then_main(onFulfilled, onRejected) {
// Update progress while queuing, calling, and resolving `then`.
self.updateProgress(null, null, 1, [onFulfilled]);
return Promise.prototype.then.call(this, function then_pre(val) {
self.updateProgress(null, onFulfilled);
return val;
}).then(onFulfilled, onRejected).then(function then_post(val) {
self.updateProgress(1);
return val;
});
});
};
Worker.prototype.thenCore = function thenCore(onFulfilled, onRejected, thenBase) {
// Handle optional thenBase parameter.
thenBase = thenBase || Promise.prototype.then;
// Wrap `this` for encapsulation and bind it to the promise handlers.
var self = this;
if (onFulfilled) { onFulfilled = onFulfilled.bind(self); }
if (onRejected) { onRejected = onRejected.bind(self); }
// Cast self into a Promise to avoid polyfills recursively defining `then`.
var isNative = Promise.toString().indexOf('[native code]') !== -1 && Promise.name === 'Promise';
var selfPromise = isNative ? self : Worker.convert(Object.assign({}, self), Promise.prototype);
// Return the promise, after casting it into a Worker and preserving props.
var returnVal = thenBase.call(selfPromise, onFulfilled, onRejected);
return Worker.convert(returnVal, self.__proto__);
};
Worker.prototype.thenExternal = function thenExternal(onFulfilled, onRejected) {
// Call `then` and return a standard promise (exits the Worker chain).
return Promise.prototype.then.call(this, onFulfilled, onRejected);
};
Worker.prototype.thenList = function thenList(fns) {
// Queue a series of promise 'factories' into the promise chain.
var self = this;
fns.forEach(function thenList_forEach(fn) {
self = self.thenCore(fn);
});
return self;
};
Worker.prototype['catch'] = function (onRejected) {
// Bind `this` to the promise handler, call `catch`, and return a Worker.
if (onRejected) { onRejected = onRejected.bind(this); }
var returnVal = Promise.prototype['catch'].call(this, onRejected);
return Worker.convert(returnVal, this);
};
Worker.prototype.catchExternal = function catchExternal(onRejected) {
// Call `catch` and return a standard promise (exits the Worker chain).
return Promise.prototype['catch'].call(this, onRejected);
};
Worker.prototype.error = function error(msg) {
// Throw the error in the Promise chain.
return this.then(function error_main() {
throw new Error(msg);
});
};
/* ----- ALIASES ----- */
Worker.prototype.using = Worker.prototype.set;
Worker.prototype.saveAs = Worker.prototype.save;
Worker.prototype.export = Worker.prototype.output;
Worker.prototype.run = Worker.prototype.then;
/* ----- FINISHING ----- */
// Expose the Worker class.
export default Worker;