How to send blade as attachment in pdf format in laravel?

by giovanny.lueilwitz , in category: Third Party Scripts , 5 months ago

How to send blade as attachment in pdf format in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by raphael_tillman , 5 months ago

@giovanny.lueilwitz 

To send a blade file as an attachment in PDF format in Laravel, you can follow these steps:

  1. First, you need to generate a PDF file using a package like DomPDF or TCPDF. Install the package by running the following command:
1
composer require barryvdh/laravel-dompdf


  1. After installing the package, create a new controller or add the PDF generation logic to an existing controller. Here is an example of how you can generate a PDF using DomPDF:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
use BarryvdhDomPDFFacade as PDF;

public function generatePdf()
{
    $data = [
        'title' => 'Sample PDF',
        'content' => 'This is just a sample PDF file generated from a blade template.'
    ];

    $pdf = PDF::loadView('pdf.template', $data);

    return $pdf->download('sample.pdf');
}


  1. Create a blade file for your PDF template (e.g., resources/views/pdf/template.blade.php) with the content you want to show in the PDF.
  2. To send the blade file as an attachment in an email, you can use the Laravel Mail class. Here is an example of how you can send the PDF file as an attachment in an email:
1
2
3
4
5
6
7
8
9
use AppMailSamplePdfEmail;
use IlluminateSupportFacadesMail;

public function sendPdfEmail()
{
    $pdf = $this->generatePdf();
    
    Mail::to('[email protected]')->send(new SamplePdfEmail($pdf));
}


  1. Create a Mailable for the email with the PDF file attached. Here is an example of how the SamplePdfEmail class might look:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
use IlluminateBusQueueable;
use IlluminateMailMailable;
use IlluminateQueueSerializesModels;
use IlluminateContractsQueueShouldQueue;

class SamplePdfEmail extends Mailable
{
    use Queueable, SerializesModels;

    protected $pdf;

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

    public function build()
    {
        return $this->view('emails.sample-pdf')
                    ->attachData($this->pdf, 'sample.pdf', [
                        'mime' => 'application/pdf',
                    ]);
    }
}


  1. Create the blade file for the email content (e.g., resources/views/emails/sample-pdf.blade.php) with the email content.
  2. Make sure you have configured mail settings in your .env file for sending emails.


That's it! By following these steps, you can send a blade file as an attachment in PDF format in Laravel.