I am defining my remote method of loopback as follows
Visitor.remoteMethod('getVisitorsPDF', {
description: 'Get visitors list in PDF file',
accepts: [
{ arg: 'res', type: 'object', http: { source: 'res' } },
{ arg: 'dateInStart', type: 'string' },
{ arg: 'dateInEnd', type: 'string' },
{ arg: 'employeeSiteId', type: 'string' },
{ arg: 'name', type: 'string' },
{ arg: 'visitorCompany', type: 'string' },
{ arg: 'employeeName', type: 'string' },
{ arg: 'typeId', type: 'number' },
{ arg: 'shift', type: 'number' }
],
returns: {},
http: { path: '/getpdf', verb: 'get' }
});
and its implementation is as follows:
Visitor.app.models.user.testAccess(res).then(
(current) => {
....
res.set('Content-Type', 'application/pdf');
res.set('Content-Disposition', 'attachment;filename="visitors.pdf"');
...
Visitor._getVisitors(query, current).then(
(visitors) => {
let visitorsFiltered = visitors.filter((v) => {
if (!v.tztimeIn) return v;
let d = v.timeIn + v.tztimeIn * 60000;
if (dStart < d && d < dEnd) return v;
});
Visitor._getVisitorsPDF(visitorsFiltered)
.then(result => {
res.send(result);
},
);
},
);
}
)
};
And the function that is generating pdf is follows:
Visitor._getVisitorsPDF = async function (visitors) {
...
const rows = tempData;
const doc = new jsPDF();
doc.autoTable(columns, rows);
doc.save('visitors.pdf');
}
how to send this doc back as application/pdf response ? I am stuck here
I have used node-html-pdf to generate and send PDFs. It has built in method to return a buffer.
In your code, doc.save('file') saves the file to the pwd.
Then you could use fs to read the saved file asynchronously then buffer it to the client
import stream from "stream";
...
fs.readFile('file', (err, fileBuffer) => {
if (err) throw err;
// console.log(fileBuffer);
let encodedBuffer = Buffer.from(JSON.stringify(fileBuffer));
// create a stream to the receiver
let readStream = new stream.PassThrough();
readStream.end(encodedBuffer);
res.set("Content-disposition", "attachment; filename=" + filename);
res.set("Content-Type", "application/pdf");
readStream.pipe(res);
});
Where res the regular the response object (of type Request in @loopback/rest), you can do:
res.download(result)
Instead of
res.send(result).