Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js html-pdf conversion issue, file is coming back corrupt

I am trying to create an application that will take an html file that is populated using a jquery get request. I am making an http get request to get the html, passing the string to the pdf.create function and using the generated buffer to send a pdf file via email. This seems to process and send the file off as an email attachment, however, when I try to open the file I am receiving an error saying the file is corrupt.

code that convert html document to pdf:
                var options = {
                  host: 'localhost',
                  path: '/salesorder/' + orderid,
                  port: '3000'
                };

                http.request(options, function(response){
                  let buffer = '';
                  response.on('data', function (chunk) {
                      buffer += chunk;
                  });

                  response.on('end', function () {
                    pdf.create(buffer, {
                        directory: "tmp"
                    }).toBuffer(function(err, newbuffer){
                        if (err){
                            reject(err);
                        }

                        if (Buffer.isBuffer(newbuffer)){
                            resolve(newbuffer);
                        } else {
                            reject(new Error('The pdf file could not be generated at this time.  Please try again later.'));
                        }
                    });
                  });
                })
                .end();


code that sends the email:
    var transporter = nodemailer.createTransport({
        service: 'gmail',
        host: this.hostname,
        auth: {
            user: this.smtpusername,
            pass: this.smtppassword
        }
    });

    var mailOptions = {
        from: fromaddress, // sender address
        to: toaddresslist, // list of receivers
        subject: subject, // Subject line
        text: text
    };

    if (attachments){
        mailOptions.attachments = [
            {   // binary buffer as an attachment
                filename: 'invoice.pdf',
                content: new Buffer(attachments.toString(), 'base64'),
                contentType: 'application/pdf'
            }
        ];
    }

I am using html-pdf node.js package to perform the conversion. What am I missing here? I am taking the html I get from the http.request method and I can see the code generated if I print it out using console.log it out. Now I notice that I am not seeing the text fields and labels populating, so it does not seem like the jquery is processing.

like image 803
user1790300 Avatar asked Feb 27 '17 16:02

user1790300


1 Answers

I'm not experienced with nodemailer, but it seems to me that you are missing encoding: 'base64' on your attachment. See the docs here.

like image 138
John Jones Avatar answered Oct 01 '22 03:10

John Jones