In this Article, how to create dynamic PDF and Sending PDF attached by Email in Laravel. We will help you to give example of generate PDF and send Email.
First of all we can install barryvdh/laravel-dompdf package from composer command in your Laravel application.
composer require barryvdh/laravel-dompdf |
After successfully install package and open config/app.php file and add this:
‘providers’=>[ Barryvdh\DomPDF\ServiceProvider::class ] ‘aliases’=>[ ‘PDF’ => Barryvdh\DomPDF\Facade::class ] |
After Setting up mail server details in .env file. You have to add send mail configuration with mail driver, mail host, mail port, mail username, mail password.
MAIL_DRIVER=smtp MAIL_HOST=smtp.hostinger.in MAIL_PORT=XXX MAIL_USERNAME=abc@example.com MAIL_PASSWORD=XXXX MAIL_ENCRYPTION=tls |
After open routes/web.php and controller URL:
Route::get(‘send_mail_with_pdf’,’Mail_pdf@index’); |
After create Controller file Mail_pdf.php name:
namespace App\Http\Controllers;
use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Route; // for pdf use Barryvdh\DomPDF\Facade as PDF; //for mail use Illuminate\Support\Facades\Mail; use Illuminate\Mail\Mailable;
class Mail_pdf extends Controller { function index(Request $request) { $user = DB::table('users') ->select('*') ->first(); $data['username'] = $user->username; $data['email'] = $user->email; //generating pdf with user data $pdf = PDF::loadView('user_details', $data);
//send mail to user Mail::send('message', $data, function($message) use ($data, $pdf) { $message->from('abc@example.com'); $message->to($data['email']); $message->subject('Receipt'); $message->attachData($pdf->output(), 'Receipt.pdf'); //attached pdf file }); }
} |
The output file name is Receipt.pdf and it will be attached with the Email.
Then, create blade file on resource directory. PDF view file in view folder name is user_details.blade.php
<html> <head> <title>How to create Dynamic PDF & Sending by Email in Laravel</title> </head> <body> <h1>User Details:</h1> <p>Username: {{ $username }}</p> <p>Email: {{ $email }}</p> </body> </html> |
Last one create message file for users mail. That file name is message.php in view folder.
<html> <head> <title>How to create Dynamic PDF & Sending by Email in Laravel</title> </head> <body> <h4> Your Automatically Generate Receipt... </h4> </body> </html> |