-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexporter.js
124 lines (99 loc) · 3.86 KB
/
exporter.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
var generateDoc = function (template, data, options, callback) {
//var phantom = require('phantom');
var handlebars = require("node-handlebars");
var templatesDir = "templates"
var hbs = handlebars.create({
partialsDir: templatesDir
});
var session;
var createPhantomSession = function (cb) {
if (session) {
return cb(session);
} else {
require('phantom').create({}, function (_session) {
session = _session;
return cb(session);
});
}
};
process.on('exit', function (code, signal) {
session.exit();
});
var generateFilename = function (ext) {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return "Export_" + s4() + s4() + s4() + ext;
};
data.baseurl = "file://" + __dirname;
hbs.engine(templatesDir + "/" + template + ".html", data, function (err, html) {
if (err) {
throw err;
}
console.log(html);
var expectedLocation = 'http://www.clofus.com/';
createPhantomSession(function (phsession) {
//ph.createPage(function(page) {
var page;
console.log("page set")
try {
phsession.createPage(function (_page) {
page = _page;
page.setContent(html, expectedLocation);
page.set('paperSize', {
format: options.paperSize,
orientation: options.orientation,
margin: '1cm'
}, function () {
var i = 0;
var renderPdf = function (success) {
console.log("file rendered " + i)
var filename = "";
filename = generateFilename("." + options.mimetype.format);
page.render(filename, options.mimetype, function () {
page.close();
page = null;
//phsession.exit();
var filepath = __dirname + "/" + filename;
callback(filepath);
});
i++;
};
page.onResourceRequested(
function (requestData, request, arg1, arg2) {
console.log(requestData.url)
request.abort();
},
function (requestData) {
console.log(requestData.url);
//page.set('onLoadFinished', renderPdf);
});
page.set("onLoadFinished", function (status) {
if (i == 0) {
console.log('Status: ' + status + " " + i);
renderPdf();
} else {
page.unset("onLoadFinished")
}
});
});
});
} catch (e) {
try {
if (page != null) {
page.close(); // try close the page in case it opened but never rendered a pdf due to other issues
}
} catch (e) {
// ignore as page may not have been initialised
}
callback('Exception rendering pdf:' + e.toString());
}
//});
});
});
}
module.exports = {
generateDoc: generateDoc
}