2017-02-27 21 views
7

我想创建一个应用程序,将采用填充使用jquery获取请求的HTML文件。我正在做一个http get请求来获取html,将字符串传递给pdf.create函数,并使用生成的缓冲区通过电子邮件发送PDF文件。这似乎是处理和发送文件作为电子邮件附件,但是,当我尝试打开文件时,我收到一个错误,说该文件已损坏。node.js html-pdf转换问题,文件回来腐败

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' 
      } 
     ]; 
    } 

我使用html-pdf node.js包来执行转换。我在这里错过了什么?我正在从http.request方法获取html,并且如果使用console.log将其打印出来,我可以看到生成的代码。现在我注意到,我没有看到文本字段和标签填充,所以它似乎不像jquery正在处理。

回答

4

我对nodemailer没有经验,但在我看来,你的附件上缺少encoding: 'base64'See the docs here.

+1

解决方案最终是编码和使用attachments.toString()而不是附件的组合。 – user1790300