繁体   English   中英

一键打开PDF并发送电子邮件附件

[英]Open PDF and send email attachment with one click

PDF生成器软件包barryvdh/laravel-dompdf ,PDF正常运行。 我有以下代码:

public function fun_pdf($test_id) {
    $test      = Test::where('id', $test_id)->first();
    $questions = (new TestQuestionsController)->questionwithanswers($test_id, $randomorder = 1);

    $test_info = (new TestInfoController)->testInfo($test_id);

    $pdf = PDF::loadView('website.tests_pdf.take-test', ['test_id' => $test_id, 'questions' => $questions, 'test' => $test, 'test_info' => $test_info]);
    $user_email = Auth::user()->email;   

    Mail::to($user_email)->send(new PdfTest($test));

    return $pdf->stream('document.pdf');
}

我想将PDF发送到电子邮件,也可以单击按钮打开。 我的电子邮件中也有此代码,在文件中的Mail文件夹中,我有以下代码:

public $test;

public function __construct(Test $test) {
    $this->test = $test;
}

/**
 * Build the message.
 *
 * @return $this
 */
public function build() {
    return $this->view('website.tests_pdf.take-test');
}

谁能帮助我该怎么做?

您可以尝试一下(我已添加评论)

public function fun_pdf($test_id) {
    $test      = Test::where('id', $test_id)->first();
    $questions = (new TestQuestionsController)->questionwithanswers($test_id, $randomorder = 1);

    $test_info = (new TestInfoController)->testInfo($test_id);

    $pdf = PDF::loadView('website.tests_pdf.take-test', ['test_id' => $test_id, 'questions' => $questions, 'test' => $test, 'test_info' => $test_info]);
    $user_email = Auth::user()->email;

    // output pdf as a string, so you can attach it to the email
    $pdfHtml = $pdf->output();

    // pass pdf string
    Mail::to($user_email)->send(new PdfTest($test, $pdfHtml));

    return $pdf->stream('document.pdf');
}

barryvdh / laravel-dompdf自述文件

如果需要将输出作为字符串,则可以使用output()函数获取渲染的PDF,因此您可以自己保存/输出它。

要将pdf附加到电子邮件,请查看laravel邮件文档中的 Raw Data Attachments

namespace App\Mail;

use App\Order;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

class PdfTest extends Mailable
{
    use Queueable, SerializesModels;

    public $test;
    public $pdfHtml;

    public function __construct(Test $test, $pdfHtml) {
        $this->test    = $test;
        $this->pdfHtml = $pdfHtml;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build() {
        return $this->view('website.tests_pdf.take-test')
                    // attach the pdf to email
                    ->attachData($this->pdfHtml, 'name.pdf', [
                        'mime' => 'application/pdf',
                    ]);;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM