4

I am trying to create a pdf dynamically using PDFkit and want to send it as an attachment in a email. Following this http://pdfkit.org/demo/browser.html example and this https://nodemailer.com/using-attachments/ documentation I wrote the following code:

 var doc = new PDFDocument();
            var stream = doc.pipe(blobStream());
            doc.text("Howdy!!");

            doc.on('end');

            stream.on('finish', function() {

                var htmlMailBody ='Hi' 

                    var textMailBody = 'hi';
                    var mailOptions = 
                    {
                        from: 'ASD', // sender address 
                        to: 'ecell@sfitengg.org', // list of receivers 
                        subject: 'Invitation ', // Subject line 
                        text: textMailBody, // plaintext body alt for html 
                        html: htmlMailBody,
                        attachments:[
                        {

                            filename:"TEST1.pdf",
                            path:stream.toBlobURL('application/pdf')


                        }]
                    };

                    // send mail with defined transport object 
                    transporter.sendMail(mailOptions, function(error, info){
                        if(error){
                            return console.log(error);
                        }
                        console.log('Message sent: ' + info.response);
                        res.redirect('/');
                    });



        });

But i am getting the following error:

 TypeError: listener must be a function
at PDFDocument.addListener (events.js:197:11)
at PDFDocument.Readable.on (_stream_readable.js:665:33)
at exports.getSendReport (d:\projects\PDFChecker\server\controllers\pdf.js:159:6)
at Layer.handle [as handle_request] (d:\projects\PDFChecker\node_modules\express\lib\router\layer.js:95:5)

How should i solve it?

ASD
  • 107
  • 2
  • 11

3 Answers3

7

Don't use BlobStream. Write to buffers instead as suggested here: how to convert pdfkit object into buffer using nodejs

const pdf = new pdfkit();

const buffers = [];
pdf.on('data', buffers.push.bind(buffers));
pdf.on('end', () => {

    let pdfData = Buffer.concat(buffers);

    const mailOptions = {
        from: '...',
        to: '...',
        attachments: [{
            filename: 'attachment.pdf',
            content: pdfData
        }]
    };

    mailOptions.subject = 'PDF in mail';
    mailOptions.text = 'PDF attached';

    return mailTransport
        .sendMail(mailOptions)
        .then(() => {
            console.log('email sent:');
        })
        .catch(error => {
            console.error('There was an error while sending the email:', error);
        });
});

pdf.text('Hello', 100, 100);
pdf.end();

I used this approach and was able to use nodemailer with buffer Attachmend and send a correct pdf.

Yurii Holskyi
  • 878
  • 1
  • 13
  • 28
Daniel Dimitrov
  • 1,848
  • 21
  • 35
  • 1
    this was the solution that worked for me. (Note that the other solution proposed that passed the pdf object as content didn't work) – mangusbrother Jan 09 '19 at 17:03
  • Using pdfkit 0.13.0 and Nodemailer 6.8.0, this solution worked for me. Giving the readable stream directly to Nodemailer (instead of a buffer) results PDFs that can't be opened. – Bernardo SOUSA Nov 14 '22 at 01:50
6

I found wrapping PDFkit into a promise easier to logic with.

const PDFDocument = require('pdfkit');

const pdfBuffer = await new Promise(resolve => {
  const doc = new PDFDocument()

  doc.text('hello world', 100, 50)
  doc.end()

  //Finalize document and convert to buffer array
  let buffers = []
  doc.on("data", buffers.push.bind(buffers))
  doc.on("end", () => {
    let pdfData = new Uint8Array(Buffer.concat(buffers))
    resolve(pdfData)
  })
})

console.log(pdfBuffer) //contains generated pdf, which can return to output
PotatoFarmer
  • 2,755
  • 2
  • 16
  • 26
5

A pdfkit instance is a stream, which you can simply pass to nodemailer:

const doc = new pdfkit();

transport.sendMail({
  from: '...',
  to: '...',
  subject: '...',
  text: '...',
  attachments: [{
    filename: 'attachment.pdf',
    content: doc,
  }],
});
Jasper Kuperus
  • 1,612
  • 1
  • 17
  • 22