Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
55 lines (47 loc) · 1.44 KB
/
Copy pathapp.js
File metadata and controls
55 lines (47 loc) · 1.44 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
const bodyParser = require('body-parser');
const config = require('./config.json');
const express = require('express');
const htmlPdf = require('html-pdf-chrome');
const pug = require('pug');
const app = express();
app.use(bodyParser.json());
const supportedFormats = ['html', 'pdf'];
const chrome = {
host: config.chrome.host,
port: config.chrome.port,
};
app.post('/', (req, res) => {
if(!req.body.template) {
return res.status(400).send('Template not set');
}
if(!supportedFormats.includes(req.body.outputFormat)) {
return res.status(400).send('Unsupported output format: ' + req.body.outputFormat);
}
var html;
try {
html = pug.renderFile('templates/' + req.body.template + '/index.pug', req.body.vars);
} catch (e) {
if (e.code == 'ENOENT') {
return res.status(500).send('Template not found: ' + e.path);
}
return res.status(500).send('Could not render template: ' + e);
}
if (req.body.outputFormat == 'html') {
res.contentType('text/html');
res.end(html);
} else {
var options = Object.assign({}, chrome);
if (req.body.printOptions) {
options.printOptions = req.body.printOptions;
}
htmlPdf.create(html, options).then((pdf) => {
res.contentType('application/pdf');
res.end(pdf.toBuffer(), 'binary');
}).catch((e) => {
res.status(500).send('Could not create pdf: ' + e);
});
}
});
app.listen(7777, () => {
console.log('Listening on port 7777');
});