本文介绍了使用Node.js应用程序中的PDFKit发送动态创建为附件的PDF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我正在尝试使用PDFkit动态创建pdf,并希望将其作为附件发送到电子邮件中.遵循此 http://pdfkit.org/demo/browser.html 示例和此 https://nodemailer.com/using-attachments/文档我编写了以下代码:

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: '[email protected]', // 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('/');
                    });



        });

但是我遇到以下错误:

 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)

我应该如何解决?

推荐答案

pdfkit实例是一个流,您可以将其简单地传递给nodemailer:

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

这篇关于使用Node.js应用程序中的PDFKit发送动态创建为附件的PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-08 03:06