问题
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!
回答1:
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;
来源:https://stackoverflow.com/questions/47311108/download-returning-empty-file