Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate pdf file using pdfkit and send it to browser in nodejs-expressjs

I am using pdfkit to generate pdf file and i want to send this pdf file to browser.

But i am getting message "TypeError: listener must be a function", Also, file is getting generate in my parent directory which i don't want.

Can anyone explain me how to generate pdf file and send it to browser without storing it at parent directory?
I am using expressjs here.

My code

var PDFDocument = require('pdfkit');                      
var fs=require('fs');
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.write('out.pdf');
res.download('out.pdf');
like image 997
Sachin Avatar asked May 13 '14 06:05

Sachin


People also ask

How do I make a PDF with PDFKit?

Creating a PDF Document using PDFKitconst PDFDocument = require('pdfkit'); const fs = require('fs'); let pdfDoc = new PDFDocument; pdfDoc. pipe(fs. createWriteStream('SampleDocument. pdf')); pdfDoc.


2 Answers

doc.write is the line causing the trouble, which is also a deprecated method so don't use it. Instead, use pipe to tell your doc where to stream the information, and remember to close it using doc.end(), i.e., like so:

doc = new PDFDocument(); doc.pipe( fs.createWriteStream('out.pdf') );  // rest of the code goes here...  doc.end(); 

Note that it's not important that doc.pipe() be at the top, it just makes sense to me (you can put it before or after doc.end(). It doesn't matter, it'll work just fine). Finally, note that you can use pipe to stream directly to a response, there's no need to create the file first and then download it, i.e.:

doc.pipe( res ) 
like image 88
yuvi Avatar answered Sep 24 '22 06:09

yuvi


So Instead try Using

doc.pipe(res);

like image 24
Rahil Lakhani Avatar answered Sep 25 '22 06:09

Rahil Lakhani