2

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!

2 Answers 2

3

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; 
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! Indeed I didn't need the physical file, so just piping the file to the response is more than enough! Thanks a lot!
1

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); } }) }); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.