首页 > 解决方案 > 在 yii2 中用作邮件附件的 PDF 生成器的更好解决方案

问题描述

我使用jspdf插件生成pdf文件并使用ajax传递给控制器​​。在控制器中,我将 pdf 作为正文邮寄,现在我想将 pdf 作为附件邮寄。有没有比jspdf更好的生成pdf的方法?我使用以下代码生成 pdf 并使用 ajax 发送

<script>
   function demoFromHTML() {
      var pdf = new jsPDF('p', 'pt', 'a4', true);
      source = $('#content')[0];
      specialElementHandlers = {
         '#bypassme': function (element, renderer) {
            return true
         }
      };
      margins = {
         top: 80,
         bottom: 60,
         left: 40,
         width: 522
      };
      pdf.fromHTML(
            source,
            margins.left,
            margins.top, {
               // y coord
               'width': margins.width, // max width of content on PDF
               'elementHandlers': specialElementHandlers
            },
            function (dispose) {
               // pdf.save('ticket');
               var pdfBase64 = pdf.output();
               var email= 'check@email.com';
               $.ajax({
                  'url': baseUrl + '/site/email',
                  'method': 'post',
                  'data': {
                     'pdfBase64': pdfBase64,
                     'email':email
                  },
                  'success': function (result) {
                     if (!result == 'true') {
                        notify('Sorry Email NOt sent', 'danger');
                     } else {
                        notify('Ticket sent', 'success');
                     }
                  },
                  'error': function (error) {
                     notify('Server Error. Sorry Email Not Sent', 'danger');
                  }
               });

            }, margins
      );


      // $('#email').val(pdfBase64);
   }
</script>

使用以下代码我在控制器中发送邮件

 if (Yii::$app->request->isAjax) {
                $post = Yii::$app->request->get();
                $email = $post['data']['email'];
                $name = 'Smart Bus';
                $subject = 'Booked Ticket';
                $base64 = $post['data']['pdfbase64'];
                $decoded = base64_decode($base64);
                Email::sendTo($email, $name, $subject, file_put_contents('invoice.pdf', $decoded));
            }

标签: emailyii2jspdf

解决方案


如果您要求使用 jspdf 以外的其他软件包,如果您使用TCPDF会很棒,因为它更受关注和使用(更出名)。它也是 PHP PDF 库(服务器端),但 jspdf 是客户端之一。


推荐阅读