只需点击一下即可打开PDF并发送电子邮件附件

时间:2017-10-19 11:19:41

标签: php laravel email pdf

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

任何人都可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

你可以试试这个(我已添加评论)

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 readme

  

如果您需要输出为字符串,您可以使用output()函数获取渲染的PDF,这样您就可以自己保存/输出。

要将pdf附加到电子邮件,请查看laravel mail documentation

中的原始数据附件
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',
                    ]);;
    }
}