我正在尝试使用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)
我该如何解决?
答案 0 :(得分:1)
不要使用BlobStream。写入缓冲区,如下所示: how to convert pdfkit object into buffer using nodejs
let pdf = new pdfkit();
let 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();
我使用了这种方法,并且能够使用带缓冲区附件的nodemailer并发送正确的pdf。
答案 1 :(得分:1)
pdfkit
个实例是一个流,您只需将其传递给nodemailer
:
const doc = new pdfkit();
transport.sendMail({
from: '...',
to: '...',
subject: '...',
text: '...',
attachments: [{
filename: 'attachment.pdf',
content: doc,
}],
});
答案 2 :(得分:1)
我发现将PDFkit包装成一个更易于逻辑的承诺。
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