簡體   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