Home > Net >  Create PDF with jspdf and send via nodemailer Node.js
Create PDF with jspdf and send via nodemailer Node.js

Time:10-04

In my Node.js server I am creating a PDF file, (But I am not saving it on my disk), My idea is to create the PDF file and after that send it via nodemailer this is my code:

app.js

const { jsPDF }   = require("jspdf");

const doc = new jsPDF();
doc.text("Hello world!", 10, 10);

email_send.send_pdf(doc);

email_send.js

exports.send_pdf = function(doc) {
  var transporter = helpers.transporter();
  var mailOptions = {
  from:    '[email protected]',
  to:      '[email protected]',
  subject: "PDF",
  html:
  '<!DOCTYPE html>' 
  '<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:o="urn:schemas-microsoft-com:office:office">' 
    '<head>' 
      '<meta charset="utf-8">' 
      '<title>THIS IS AN EMAIL</title>' 
      '<meta name="viewport" content="width=device-width,initial-scale=1" />' 
      '<meta name="x-apple-disable-message-reformatting" />' 
      '<style>' 
        'table,' 
        'td,' 
        'div,' 
        'h1,' 
        'p {' 
          'font-family: Arial, sans-serif;' 
        '}' 
      '</style>' 
    '</head>' 
    '<body style="margin: 0; padding: 0; padding-top: 20px">' 
      '<p style="margin: 0 0 12px 0; font-size: 10px; line-height: 24px; font-family: Arial, sans-serif">' 
        '<b>Your email with pdf file is:</b> ' 
      '</p>' 
    '</body>' 
  '</html>',
  attachments: [
    {
      filename: "mypdf.pdf",
      content: doc.output('arraybuffer')
    }
  ]
  };
  transporter.sendMail(mailOptions)
  .then(function(info) {
    console.log('success');
  })
  .catch(function(error) {
    console.log("----ERROR------");
  }); 
}

I have seen some blogs say: put something like this doc.output('arraybuffer') or doc.output('datauristring') But always I have the following error:

TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be one of type string or Buffer. Received type object )

So, How can I fix it, all is developed in Node.js server.

CodePudding user response:

It looks like nodemailer wants a "real" Buffer for attachments, which you can create from ArrayBuffer:

Buffer.from(doc.output('arraybuffer'))
  • Related