Search code examples
htmlnode.jspdfstreammailgun

Change file name of toStream() in node.js html-pdf npm module


I am trying to change the file name of the pdf generated by the npm module html-pdf.

The issue is I do not want to save a copy of the pdf, just stream it to an email service ( mailgun) and then send it off. I have everything working but when I receive the email the file has a default name that I want to change. Does anyone have any experience trying to do this?

Thanks

var pdf = require('html-pdf');
var Mailgun = require('mailgun-js');

pdf.create(result).toStream(function(err, stream) {
    var self = this;
    if (err) return console.log(err);

    //set mailgun parameters
     var mail_data = {
        from: '[email protected]',
        to: '[email protected]',
        subject: 'subject line',
        html: result,
        attachment: stream
    }
    //send email
    mailgun.messages().send(mail_data, function (err, body) {
        if (err) {
            res.render('error', { error : err});
            console.log("got an error: ", err);
        }
        else {
            console.log(body);
            res.send('ok');
        }
    });

});

Solution

  • var pdf = require('html-pdf');
    var Mailgun = require('mailgun-js');
    
    pdf.create(result).toBuffer(function(err, buffer) {
        var self = this;
        if (err) return console.log(err);
    
        var attch = new mailgun.Attachment({data: buffer, filename: 'myattach.pdf'});
    
        //set mailgun parameters
         var mail_data = {
            from: '[email protected]',
            to: '[email protected]',
            subject: 'subject line',
            html: result,
            attachment: attch
        }
        //send email
        mailgun.messages().send(mail_data, function (err, body) {
            if (err) {
                res.render('error', { error : err});
                console.log("got an error: ", err);
            }
            else {
                console.log(body);
                res.send('ok');
            }
        });
    
    });
    

    From https://github.com/bojand/mailgun-js#attachments