-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathserver.js
More file actions
280 lines (245 loc) · 7.97 KB
/
Copy pathserver.js
File metadata and controls
280 lines (245 loc) · 7.97 KB
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
'use strict';
const express = require('express');
const https = require('https');
const fs = require('fs');
const puppeteer = require('puppeteer');
const bodyParser = require('body-parser');
// Constants
const HOST = '0.0.0.0';
const PORT = 2078;
const SPORT = 2079;
const DEFAULT_WIDTH = 210 * 4;
const DEFAULT_HEIGHT = 297 * 4;
let ENABLE_HTTPS = false;
if (process.env['ENABLE_HTTPS'] == "TRUE")
ENABLE_HTTPS = true;
// App
const app = express();
let renderCount = 0;
app.use(bodyParser.json({
limit: '50mb'
}));
app.use(bodyParser.urlencoded({
limit: '50mb',
extended: true,
parameterLimit: 50000
}));
app.use(function (req, res, next) {
if (req.is('text/*')) {
req.text = '';
req.setEncoding('utf8');
req.on('data', function (chunk) {
req.text += chunk
});
req.on('end', next);
} else {
next();
}
});
function render(req, res) {
renderCount++;
let renderID = renderCount;
const format = req.query['format'] || 'pdf';
let pageSize = req.query['pagesize'] || 'A4';
const pageLandscape = req.query['pagelandscape'] === 'true';
let width = req.query['width'] || DEFAULT_WIDTH;
let height = req.query['height'] || DEFAULT_HEIGHT;
if (width !== DEFAULT_WIDTH || height !== DEFAULT_HEIGHT)
// need to set pageSize to undefined to allow the pdf function to make
// use of the width and height
pageSize = undefined;
let deviceScaleFactor = req.query['deviceScaleFactor'] || 1.0;
let topMargin = req.query['top'] || 0;
let bottomMargin = req.query['bottom'] || 0;
let bodyHtml;
let headerHtml;
let footerHtml;
let isHeaderFooter = false;
if (req.is('application/json')) {
// If you are using a header and/or footer, then you probably want to specify
// top and bottom margin
headerHtml = req.body.header;
bodyHtml = req.body.body;
footerHtml = req.body.footer;
} else if (req.text !== undefined) {
bodyHtml = req.text;
} else {
res.status(400).send('The body must have Content-Type:text/html');
return;
}
if (headerHtml || footerHtml)
isHeaderFooter = true;
(async () => {
let browser;
try {
browser = await puppeteer.launch({
args: ['--no-sandbox', '--disable-setuid-sandbox']
});
let page;
try {
page = await browser.newPage();
} catch (error) {
let e = "New Page " + error.toString();
console.error(e);
res.status(500).send(e);
return;
}
try {
await page.setContent(bodyHtml, {
waitUntil: 'domcontentloaded',
timeout: 600000
});
} catch (error) {
let e = "Set Content " + error.toString();
console.error(e);
res.status(500).send(e);
return;
}
if (format == 'pdf') {
console.info(`R:${renderID} Rendering pdf ${pageSize} ${pageLandscape}`);
await page.evaluateHandle('document.fonts.ready');
let pdf;
try {
pdf = await page.pdf({
format: pageSize,
width: width,
height: height,
landscape: pageLandscape,
printBackground: true,
displayHeaderFooter: isHeaderFooter,
headerTemplate: headerHtml,
footerTemplate: footerHtml,
margin: {
top: topMargin,
bottom: bottomMargin
},
timeout: 600000
});
}
catch (error) {
let e = "Failed to render PDF " + error.toString();
console.error(e);
res.status(500).send(e);
return;
}
res.setHeader('content-type', 'application/pdf');
res.send(pdf);
} else if (format == 'png') {
deviceScaleFactor = parseFloat(deviceScaleFactor);
width = parseInt(width);
height = parseInt(height);
topMargin = parseInt(topMargin);
bottomMargin = parseInt(bottomMargin);
if (deviceScaleFactor < 0.25 || deviceScaleFactor > 8) {
res.status(400).send('Invalid deviceScaleFactor. Must be between 0.25 and 8');
return;
}
if (width < 4 || height < 4) {
res.status(400).send('width and height must be at least 4');
return;
}
let maxSize = 2000;
if (width * deviceScaleFactor > maxSize || height * deviceScaleFactor > maxSize || width > maxSize || height > maxSize) {
// clamp our size, because it seems like something is going wrong when the image
// size gets too large.
// The symptom is this:
// The user tries to produce an A0 print preview, and the request for the preview
// just never returns (ie, from the HTTP client's point of view).
// The server logs aren't clear, but there are some suspicious thing, like:
// 2020-07-06 15:40:32.532 SAST (node:30) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 exit listeners added to [process]. Use emitter.setMaxListeners() to increase limit
// 2020-07-07 20:36:59.575 SAST TimeoutError: Timed out after 30000 ms while trying to connect to the browser! Only Chrome at revision r756035 is guaranteed to work.
// 2020-07-07 20:37:05.397 SAST at Timeout.onTimeout (/usr/src/htmlrender/node_modules/puppeteer/lib/launcher/BrowserRunner.js:200:20)
// 2020-07-07 20:37:05.398 SAST at listOnTimeout (internal/timers.js:549:17)
// 2020-07-07 20:37:05.398 SAST at processTimers (internal/timers.js:492:7)
// I suspect that something is going wrong that is catching puppeteer unaware. Or maybe we're simply not catching exceptions correctly.
// What happens is that the VM becomes completely unresponsive, and we are unable to SSH into it, and we have to reset it.
// The size of an A1 preview is 2384 x 1684, and that is fine, but an A0 causes us to hang.
// This is a small VM, with only 3.6 GB RAM.
// In these calculations, we need to take deviceScaleFactor into consideration, because page.setViewport()
// takes css pixels for it's width/height, so the real image width is width*deviceScaleFactor.
// OK.. one other massive thing...
// I don't really understand why, but I'm just throwing more fuel at this problem
let scale = deviceScaleFactor;
if (scale < 1)
scale = 1;
let aspect = width / height;
if (aspect >= 1) {
width = maxSize / scale;
height = width / aspect;
} else {
height = maxSize / scale;
width = height * aspect;
}
width = Math.floor(width);
height = Math.floor(height);
}
console.info(`R:${renderID} Rendering png ${width} x ${height} @ ${deviceScaleFactor}`);
try {
await page.setViewport({
width: width,
height: height,
deviceScaleFactor: deviceScaleFactor,
});
} catch (error) {
let e = "Viewport " + error.toString();
console.error(e);
res.status(500).send(e);
return;
}
let png;
try {
png = await page.screenshot({
type: 'png',
omitBackground: true,
fullPage: true
});
} catch (error) {
let e = "Screenshot " + error.toString();
console.error(e);
res.status(500).send(e);
return;
}
res.setHeader('content-type', 'image/png');
res.send(png);
console.info(`R:${renderID} Rendering ${width} x ${height} @ ${deviceScaleFactor} complete`);
} else {
res.status(400).send(`Unknown format ${format}. Valid formats are pdf,png`);
}
console.info(`R:${renderID} Closing brower (clean exit)`);
await browser.close();
} catch (error) {
console.error(error);
res.status(400).send(error);
console.info(`R:${renderID} Closing brower (exception handler)`);
if (browser) {
await browser.close();
}
}
})();
}
function version(req, res) {
res.send({
version: '1.4.1'
});
}
function ping(req, res) {
res.send({
timestamp: +new Date()
});
}
// The original API was called html2pdf, but this has grown to be able to produce PNGs,
// so that's why it got another name "render".
app.post('/html2pdf', render);
app.post('/render', render);
app.get('/version', version);
app.get('/ping', ping);
app.listen(PORT, HOST);
console.log(`Running on http://${HOST}:${PORT}`);
if (ENABLE_HTTPS) {
let options = {
key: fs.readFileSync('/opt/htmlrender/ssl/ssl.key'),
cert: fs.readFileSync('/opt/htmlrender/ssl/ssl.crt')
};
https.createServer(options, app).listen(SPORT);
console.log(`Running on https://${HOST}:${SPORT}`);
}