1

I am now doing Nodejs, trying generate a PDF using PDFMake. After it's was generate, I want it to be downloaded immediately. However, after downloading the files, I couldn't open the file. It says "Failed to load PDF document." The code I written are below.

var docDefinition = { content: 'test', };

var pdfDoc = printer.createPdfKitDocument(docDefinition);
pdfDoc.pipe(fs.createWriteStream('name.pdf'));

pdfDoc.end();

res.download('name.pdf');
Alexander Schmidt
  • 5,631
  • 4
  • 39
  • 79
Jerrold
  • 11
  • 3

2 Answers2

6

Check out my solution to this problem pdfMake - cannot open file.

Why pdfmake cannot open file is because the file stream fs is still writing to the memory block, which makes it unreadable and the downloaded PDF would be corrupted with size of 0KB.

Solution: Add an event listener to the fs.createWriteSteam and wait for fs to finish writing then send file.

var temp123;
pdfDoc.pipe(temp123 = fs.createWriteStream('./PDF/' + name), { encoding:'utf16' });

pdfDoc.end();

temp123.on('finish', async function () {
  // do send PDF file 
  res.download('name.pdf');
});
Mike
  • 14,010
  • 29
  • 101
  • 161
Marcia Ong
  • 781
  • 8
  • 15
  • 1
    Thanks @Marcis you saved my lots of time , deserve upvote . – Bhagvat Lande Aug 20 '19 at 13:36
  • in my case is 70 kb something but still Failed to load the PDF document error is showing. I am doing this ```const pdfDoc = pdfMake.createPdf(docDefinition); return pdfDoc.getBase64((data)=>{ return data; }); ``` – Ali Yar Khan Dec 03 '21 at 11:19
0

if you have access to the response object you can use the response object as a parameter of pdfDoc.pipe(response)

pdfDoc.pipe(response);
Ravi S. Singh
  • 617
  • 8
  • 15