1

I'm using the TCPDF library to create invoices in my CakePHP application. If I go to /invoices/view/1 my view.ctp includes the code to generate and display the pdf in the browser. I want to add the ability to send the pdf as an email attachment so I created the action /invoices/send_invoice and copied the code from view.ctp into an email template.

Now where I'm stuck, I don't know how to have the PDF generated first before attaching it. At the end of my view.ctp page template I use

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

which sends the pdf to view in browser without creating the file. I can save the file if I use 'F' or 'FI' as the last parameter to $pdf->Output() but it's not guaranteed that the user will view the invoice before trying to send it as an email.

In my send_invoice action I need to have the pdf generated as a file in order to attach it with:

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

having the code that generates the pdf file in my email template means the file doesn't exist yet when I try to attach it. Is there some way to attach the file from the email template itself? I was thinking maybe I can write a function on my Invoice model to generate the pdf but I want to use some View Helpers (like the Number helper) to format my data. Can I execute the code in a view and then return to the controller/action without displaying the view?

4

3 回答 3

2

带有 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 就会生成:

阅读更多

于 2015-08-03T09:18:59.113 回答
0

您可以通过创建视图对象来实现,然后手动调用所需的函数以使其正确呈现。

 $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

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

于 2013-10-02T19:49:49.067 回答
0

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

于 2014-07-25T20:49:41.863 回答