Reputation: 69
I'm building a node.js+express application in which the user will input some data, the generates a PDF with pdfkit and the file is sent to the user. I'm being able to generate the file successfully, the problem is that when I download the file generated, it's empty. I can't even open the PDF, the reader (Preview, native reader in macOS) says that the file is empty. I'm using the following code:
var express = require('express');
var router = express.Router();
var guid = require('guid');
var PDFDocument = require('pdfkit');
var fs = require('fs');
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.post('/criar', function(req, res, next) {
var filename = guid.raw()+'.pdf';
var doc = new PDFDocument();
doc.pipe(fs.createWriteStream(filename));
doc.font('fonts/UbuntuMono-R.ttf')
.fontSize(25)
.text('Some text with an embedded font!', 100, 100);
doc.end();
res.download(filename, 'rifas.pdf', function(err){
if(!err){
fs.unlink(filename);
}
})
});
module.exports = router;
Do you have any idea on why my downloaded files are empty, while in the server they're being generated correctly?
Thanks!
Upvotes: 2
Views: 2205
Reputation: 134
If you need both the physical file and a download response (like I do), you can wait for the close
event of the stream:
let stream = fs.createWriteStream(filename);
doc.pipe(stream);
// Do whatever you need with doc
doc.end();
stream.on("close", () => {
res.download(filename, 'rifas.pdf', function(err){
if(!err){
fs.unlink(filename);
}
})
});
Upvotes: 1
Reputation: 3053
Do you really need the physical file? If not then you can stream directly to the client:
var express = require('express');
var router = express.Router();
var PDFDocument = require('pdfkit');
var fs = require('fs');
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.post('/criar', function(req, res, next) {
var doc = new PDFDocument();
doc.pipe(res);
doc.font('fonts/UbuntuMono-R.ttf')
.fontSize(25)
.text('Some text with an embedded font!', 100, 100);
doc.end();
});
module.exports = router;
Upvotes: 3