4

我正在使用PDFKit生成 PDF。我正在使用 Nodejitsu 进行托管,所以我无法将 PDF 保存到文件中,但我可以将它们保存到可读流中。我想将该流附加到 Sendgrid 电子邮件中,如下所示:

sendgrid.send({
    to: email,
    files: [{ filename: 'File.pdf', content: /* what to put here? */ }]
    /* ... */
});

我试过doc.output()无济于事。

4

3 回答 3

6

要将 SendGrid nodejs API 与流文件一起使用,只需将流转换为缓冲区。您可以使用流到数组将可读流转换为缓冲区。

var streamToArray = require('stream-to-array');

streamToArray(your_stream, function (err, arr) {
  var buffer = Buffer.concat(arr)
  sendgrid.send({
    to: email,
    files: [{ filename: 'File.pdf' content: buffer }]
  })
})
于 2014-05-27T19:50:08.967 回答
1

尝试通过streamToArray包发送流并将其编码为 base64。(没有base64编码,Sendgrid会抛出no content string的错误)

 // createPdf() module returns the doc stream
 // styling etc etc
 doc.end()      
 return doc // then once doc.end() is called, return the stream

 const sgMail = require('@sendgrid/mail');
 const streamToArray = require('stream-to-array');

 streamToArray(createPdf(), function (err, arr) { // createPdf() returns the doc made by pdfKit
        var buffer = Buffer.concat(arr).toString('base64')
        msg["subject"] = 'Here is your attachment'
        msg["html"] = body // your html for your email, could use text instead
        msg["attachments"] = [{
            filename: 'attachment.pdf',
            content: buffer,
            type: 'application/pdf',
            disposition: 'attachment'
        }]

        sgMail.send(msg) // sendgrid
      })
于 2021-09-07T19:36:17.523 回答
0

我最近自己在这个问题上苦苦挣扎,我只想分享对我有用的东西:

//PdfKit

var doc = new PDFDocument({
    size: 'letter'
});
doc.text('My awesome text');
doc.end();


//Sendgrid API

var email = new sendgrid.Email();

    email.addTo         ('XXX@gmail.com');
    email.setFrom       ('XXX@gmail.com');
    email.setSubject    ('Report');
    email.setText       ('Check out this awesome pdf');
    email.addFile       ({
            filename: project.name + '.pdf',
            content: doc,
            contentType: 'application/pdf'
        });

sendgrid.send(email, function(err, json){
    if(err) {return console.error(err);}
    console.log(json);
});

关键是使文件附件中的内容成为“doc”

于 2016-03-05T16:54:54.693 回答