Reputation:
I'm trying to get the following to work, I have a GET REST request hitting an endpoint which runs receipt
. I get no errors from the below but when I check the returned blob but nothing to show the text I added is present.
var PDFDocument = require('pdfkit');
// User Receipt
exports.receipt = function(req, res) {
var guid = req.params.guid;
console.log(guid);
var doc = new PDFDocument();
var stream = doc.pipe( res );
doc.moveTo(300, 75)
.lineTo(373, 301)
.lineTo(181, 161)
.lineTo(419, 161)
.lineTo(227, 301)
.fill('red', 'even-odd');
var loremIpsum = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam in...';
doc.y = 320;
doc.fillColor('black')
doc.text(loremIpsum, {
paragraphGap: 10,
indent: 20,
align: 'justify',
columns: 2
});
doc.end();
res.setHeader('Content-Type', 'application/pdf');
stream.on('finish', function() {
stream.pipe(res);
});
};
Client side I have the following code:
var file = new Blob([response], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
$window.open(fileURL);
But the page returns with Failed to load PDF document
.
Upvotes: 1
Views: 1656
Reputation: 17168
You should be setting the headers before you pipe. Also, you should only be piping to res
once.
var PDFDocument = require('pdfkit');
// User Receipt
exports.receipt = function(req, res) {
var guid = req.params.guid;
console.log(guid);
var doc = new PDFDocument();
doc.moveTo(300, 75)
.lineTo(373, 301)
.lineTo(181, 161)
.lineTo(419, 161)
.lineTo(227, 301)
.fill('red', 'even-odd');
var loremIpsum = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam in...';
doc.y = 320;
doc.fillColor('black')
doc.text(loremIpsum, {
paragraphGap: 10,
indent: 20,
align: 'justify',
columns: 2
});
doc.end();
res.setHeader('Content-Type', 'application/pdf');
return doc.pipe(res);
};
Upvotes: 1