【问题标题】:CakePHP generate pdf then send as email attachmentCakePHP 生成 pdf 然后作为电子邮件附件发送
【发布时间】:2013-10-02 18:10:38
【问题描述】:

我正在使用 TCPDF 库在我的 CakePHP 应用程序中创建发票。如果我转到/invoices/view/1,我的 view.ctp 包含在浏览器中生成和显示 pdf 的代码。我想添加将 pdf 作为电子邮件附件发送的功能,因此我创建了操作 /invoices/send_invoice 并将代码从 view.ctp 复制到电子邮件模板中。

现在我陷入困境,我不知道如何在附加之前先生成 PDF。 在我使用的 view.ctp 页面模板的末尾

$pdf->Output(APP . 'File/pdf_invoices' . DS . 'invoice-'.$invoice['Invoice']['id'].'.pdf', 'I');

发送 pdf 以在浏览器中查看而不创建文件。如果我使用 'F' 或 'FI' 作为 $pdf->Output() 的最后一个参数,我可以保存文件,但不能保证用户在尝试将其作为电子邮件发送之前会查看发票。

在我的 send_invoice 操作中,我需要将 pdf 生成为文件以便附加:

$email->attachments(APP . 'File/pdf_invoices' . DS . 'invoice-'.$invoice['Invoice']['id'].'.pdf');

在我的电子邮件模板中包含生成 pdf 文件的代码意味着当我尝试附加该文件时该文件尚不存在。有没有办法从电子邮件模板本身附加文件?我在想也许我可以在我的 Invoice 模型上编写一个函数来生成 pdf,但我想使用一些 View Helpers(如 Number helper)来格式化我的数据。我可以在视图中执行代码然后返回控制器/动作而不显示视图吗?

【问题讨论】:

    标签: php email cakephp pdf cakephp-2.4


    【解决方案1】:

    带有 PDF 附件的 Cakephp 电子邮件和使用 CakePDF 插件生成 PDF

    第 1 步:安装和设置 CakePDF

    第 2 步:配置

    第 3 步:应用控制器配置

    App::uses('CakePdf', 'CakePdf.Pdf');
    public $components = array("Email","RequestHandler");
    

    第 4 步:CakePHP 的控制器代码

        // PDF Generation code
        $this->set('extraparams', $categories);
    
        $this->pdfConfig = array(
            'orientation' => 'portrait',
            'filename' => 'invoice_'. $orderID
        );
    
        $CakePdf = new CakePdf();
        $CakePdf->viewVars(array('extraparams' => $categories));
        $CakePdf->template('confirmpdf', 'default');
        //get the pdf string returned
        $pdf = $CakePdf->output();
        //or write it to file directly
    
    
        $pdf = $CakePdf->write(APP . 'webroot'. DS .'files' . DS . 'orders' . DS . 'order_'.$orderID.'.pdf');
        $pdf = APP . 'webroot'. DS .'files' . DS . 'orders' . DS . 'order_'.$orderID.'.pdf';
        // PDF Generation code
    
        return $pdf;
    

    非常有用的链接,只需按照上述步骤操作,您的 PDF 就会生成:

    Read More

    【讨论】:

    • 始终欢迎提供指向潜在解决方案的链接,但请add context around the link,以便您的其他用户知道它是什么以及为什么存在。始终引用重要链接中最相关的部分,以防目标站点无法访问或永久离线。考虑到仅仅是指向外部站点的链接Why and how are some answers deleted? 的一个可能原因。
    • @XaviLópez:感谢您的建议,上面已更新 - 希望对您有所帮助!
    【解决方案2】:

    你可以通过创建一个视图对象,然后手动调用你需要的函数来让它正确渲染。

     $view = new View(null, false);
     $view->set(//set view data here like normal);
     $view->viewPath = 'pdf';  //folder to look in in Views directory
     $output = $view->render('pdf', 'pdf');  //layout name and view name
    

    然后只需保存输出,或根据需要使用它。

    【讨论】:

    • 谢谢!我可以用这行 $email->attachments(array('invoice-'.$invoice_id.'.pdf'=>array('data'=>$output))); 附加 pdf
    【解决方案3】:

    如果您可以使用wkhtmltopdf,另一种可能性是生成一个临时pdf文件,将其附加并删除。 wkhtmltopdf 主要工作:直接将 html 文件转换为 pdf。 html 是您的视图。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-02
      • 2020-12-05
      • 1970-01-01
      • 2016-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多