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

Member

by denis , 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

Member

by daisha , 5 months ago

@denis 

To send a blade view as an attachment in PDF format in Laravel, you can use the TCPDF library along with the laravel-snappy package.


Here are the steps to achieve this:

  1. Install the laravel-snappy package by running the following command:
1
composer require knplabs/knp-snappy


  1. Next, you need to publish the configuration file by running the following command:
1
php artisan vendor:publish --provider="KnpSnappyLaravelServiceProvider"


  1. Create a new Blade view that you want to convert to PDF and save it in the resources/views directory.
  2. In your controller, you can use the following code to convert the Blade view to PDF and send it as an attachment in an email:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
use SnappyImage;
use Mail;

public function sendPdf()
{
    $pdf = SnappyImage::loadView('pdf.blade', ['data' => $data]);

    $pdf->setOption('header-html', 'path_to_header.blade');
    $pdf->setOption('footer-html', 'path_to_footer.blade');

    $pdfData = $pdf->output();

    Mail::send([], [], function ($message) use ($pdfData) {
        $message->to('[email protected]')
                ->subject('PDF attachment')
                ->attachData($pdfData, 'pdf_attachment.pdf');
    });

    return "PDF sent successfully";
}


Replace the path_to_header.blade and path_to_footer.blade with the actual paths to your header and footer HTML files for the PDF. Also, replace pdf.blade with the actual file name of your Blade view.

  1. Don't forget to configure the mail settings in your .env file or config/mail.php file before sending the email.


That's it! You can now send a blade view as an attachment in PDF format in Laravel using the TCPDF library and laravel-snappy package.