How To Generate A PDF And Send An Email In Laravel 10

How To Generate A PDF And Send An Email In Laravel 10

Here is an example of how to generate a PDF and send an email in Laravel 10:

  1. Install the barryvdh/laravel-dompdf package. This package provides a simple way to generate PDF files in Laravel. You can install it using the following command:
composer require barryvdh/laravel-dompdf
  1. Publish the dompdf configuration file. This file contains the configuration options for the barryvdh/laravel-dompdf package. You can publish it using the following command:
php artisan vendor:publish --provider="Barryvdh\DomPDF\DomPDFServiceProvider"
  1. Create a controller to generate the PDF file. Create a new file called PDFController.php in your app/Http/Controllers directory. In this file, add the following code:

PHP

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use PDF;

class PDFController extends Controller
{
    public function generatePDF()
    {
        $data = [
            'title' => 'My PDF Document',
            'content' => 'This is the content of my PDF document.',
        ];

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

        return $pdf->download('my-pdf.pdf');
    }
}
  1. Create a view file to render the PDF content. Create a new file called pdf.example.blade.php in your resources/views directory. In this file, add the following code:

HTML

<!DOCTYPE html>
<html>
<head>
    <title>My PDF Document</title>
</head>
<body>
    <h1>{{ $title }}</h1>
    <p>{{ $content }}</p>
</body>
</html>
  1. Create a route to your controller. In your routes/web.php file, add the following route:
Route::get('/pdf', 'PDFController@generatePDF');
  1. Test the route. In your terminal, run the following command to test the route:
php artisan serve

Then, open a browser and navigate to the following URL:

http://localhost:8000/pdf

This will generate a PDF file and download it to your computer.

Here is an explanation of the code:

  • The PDFController class extends the Controller class.
  • The generatePDF() method generates the PDF file and returns it as a download.
  • The loadView() method loads the pdf.example view file and passes the data array to it.
  • The download() method downloads the PDF file to the user’s computer.

See more posts here

Leave a Reply