【问题标题】:Sending a PDF created dynamically as an attachment using PDFKit in a nodejs application在 nodejs 应用程序中使用 PDFKit 将动态创建的 PDF 作为附件发送
【发布时间】:2017-03-09 14:15:33
【问题描述】:

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

 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('/');
                    });



        });

但我收到以下错误:

 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)

我该如何解决?

【问题讨论】:

    标签: node.js pdf blob nodemailer pdfkit


    【解决方案1】:

    不要使用 BlobStream。按照此处的建议写入缓冲区: 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();
    

    我使用了这种方法,并且能够使用带有缓冲区 Attachmend 的 nodemailer 并发送正确的 pdf。

    【讨论】:

    • 这是对我有用的解决方案。 (请注意,提出的将 pdf 对象作为内容传递的其他解决方案不起作用)
    【解决方案2】:

    我发现将 PDFkit 包装成更易于逻辑化的 Promise。

    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
    

    【讨论】:

      【解决方案3】:

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

      const doc = new pdfkit();
      
      transport.sendMail({
        from: '...',
        to: '...',
        subject: '...',
        text: '...',
        attachments: [{
          filename: 'attachment.pdf',
          content: doc,
        }],
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-05-05
        • 1970-01-01
        • 2013-11-24
        • 1970-01-01
        • 2016-06-16
        • 2014-11-11
        • 2023-04-07
        • 1970-01-01
        相关资源
        最近更新 更多