forked from hajareshyam/pdf-creator-node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
86 lines (75 loc) · 2.34 KB
/
index.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
/**
* @author Shyam Hajare <[email protected]>
*/
/**
* create function is used to create pdf from handlebar templates.
* @param {document, options}
* @return {callback}
*/
var Handlebars = require("handlebars");
var pdf = require("html-pdf");
Handlebars.registerHelper("ifCond", function (v1, operator, v2, options) {
switch (operator) {
case "==":
return v1 == v2 ? options.fn(this) : options.inverse(this);
case "===":
return v1 === v2 ? options.fn(this) : options.inverse(this);
case "!=":
return v1 != v2 ? options.fn(this) : options.inverse(this);
case "!==":
return v1 !== v2 ? options.fn(this) : options.inverse(this);
case "<":
return v1 < v2 ? options.fn(this) : options.inverse(this);
case "<=":
return v1 <= v2 ? options.fn(this) : options.inverse(this);
case ">":
return v1 > v2 ? options.fn(this) : options.inverse(this);
case ">=":
return v1 >= v2 ? options.fn(this) : options.inverse(this);
case "&&":
return v1 && v2 ? options.fn(this) : options.inverse(this);
case "||":
return v1 || v2 ? options.fn(this) : options.inverse(this);
default:
return options.inverse(this);
}
});
var create = function (document, options) {
return new Promise((resolve, reject) => {
if (!document || !document.html || !document.data) {
reject(new Error("Some, or all, options are missing."));
}
// use helpers
if(document.helper){
document.helper.forEach(element => {
Handlebars.registerHelper(element.name,element.function);
});
}
// Compiles a template
var html = Handlebars.compile(document.html)(document.data);
var pdfPromise = pdf.create(html, options);
// Create PDF from html template generated by handlebars
// Output will be PDF file
switch (document.type) {
case "buffer":
pdfPromise.toBuffer((err, res) => {
if (!err) resolve(res);
else reject(err);
});
break;
case "stream":
pdfPromise.toStream((err, res) => {
if (!err) resolve(res);
else reject(err);
});
break;
default:
pdfPromise.toFile(document.path, (err, res) => {
if (!err) resolve(res);
else reject(err);
});
break;
}
});
};
module.exports.create = create;