-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexport.js
More file actions
65 lines (62 loc) · 2.13 KB
/
Copy pathexport.js
File metadata and controls
65 lines (62 loc) · 2.13 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
const express = require('express');
const router = express();
const hummus = require('hummus');
const memoryStreams = require('memory-streams');
const { parallel } = require('async');
const { render } = require('./jsreport');
router.post('/', (req, res) => {
const data = req.body;
console.log(`${new Date().toISOString()} | starting new export`);
parallel(
data.map(({html, data}) => {return callback => render(html, data, callback)}),
(err, bufferArray) => {
if (err){
console.error(err);
return res.json({
status: 500,
error: err,
msg: "could not convert all HTMLs to PDF"
});
}
try{
console.log(`${new Date().toISOString()} | all PDFs exported by jsreport and ready to merge`);
const mergedPDF = combinePDFBuffers(bufferArray);
console.log(`${new Date().toISOString()} | PDFs merged successfully`);
return res.json({
status: 200,
msg: "pdf successfully created",
data: {
pdf: mergedPDF
}
});
} catch (e) {
console.error(e);
return res.json({
status: 500,
error: e,
msg: "could not merge PDFs"
});
}
}
);
});
function combinePDFBuffers (bufferArray) {
let outStream = new memoryStreams.WritableStream();
try {
let pdfStreamArray = bufferArray.map(buffer => new hummus.PDFRStreamForBuffer(buffer));
let pdfWriter = hummus.createWriterToModify(
pdfStreamArray.shift(),
new hummus.PDFStreamForResponse(outStream)
);
pdfStreamArray.map(pdfStream => pdfWriter.appendPDFPagesFromPDF(pdfStream));
pdfWriter.end();
let newBuffer = outStream.toBuffer();
outStream.end();
return newBuffer;
}
catch(e){
outStream.end();
throw e;
}
}
module.exports = router;