Nihir's avatar
Level 50

How to generate dynamic PDF and send that PDF to user via email?

Hi all I have an ecommerce store, and I want to send the pdf via email to user mail after the checkout success is complete.

Is there any suggestion of a Package for it? Let me know if it will be helpful for me

0 likes
6 replies
rodrigo.pedra's avatar

I've used this package to generate invoices:

https://github.com/barryvdh/laravel-dompdf

It can generate an invoice from a HTML string. So I used a blade view to leverage Laravel features.

Just be aware that, due to dompdf limitations, not all CSS is exported correctly.

The code I had was basically this:

<?php

namespace App\Http\Controllers;

use App\Models\Order;
use Illuminate\Contracts\View\Factory;

class DownloadInvoiceController extends Controller
{
    public function show(Factory $viewFactory, Order $order)
    {
        $html = $viewFactory->make('invoice.show', [
            'order' => $order,
            'contact' => $order->contact,
        ])->render();

        /** @var  \Barryvdh\DomPDF\PDF $pdf */
        $pdf = \resolve('dompdf.wrapper');
        $pdf->loadHtml($html);

        return $pdf->download();
    }
}

And I used a HTML table to make the invoice layout, just like the old days...

Hope this helps =)

1 like
Nihir's avatar
Level 50

Hi @rodrigo.pedra Thanks for replying, but the thing is I have to send the generated PDF to the User, or Admin Dompdf is developed the pDF without any error, and I tried a new function loadView for generating and sending the pdf via email, but it displays the error Non-static method 'loadView' should not be called statically.

Nihir's avatar
Level 50

Hi @iftekhs here is my controller Code

 public function index()
    {
        $data["email"] = "[email protected]";
        $data["title"] = "From The Test";
        $data["body"] = "This is Demo";

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

        Mail::send('emails.myTestMail', $data, function($message)use($data, $pdf) {
            $message->to($data["email"], $data["email"])
                    ->subject($data["title"])
                    ->attachData($pdf->output(), "text.pdf");
        });

        dd('Mail sent successfully');
    }
iftekhs's avatar

@Nihir are you loading the correct class? try this ->

use Barryvdh\DomPDF\Facade as PDF;

$data["email"] = "[email protected]";
$data["title"] = "From The Test";
$data["body"] = "This is Demo";
$pdf = PDF::loadView('emails.myTestMail', $data);

  Mail::send('emails.myTestMail', $data, function($message)use($data, $pdf) {
            $message->to($data["email"], $data["email"])
                    ->subject($data["title"])
                    ->attachData($pdf->output(), "text.pdf");
  });

 dd('Mail sent successfully');

// or you could do this -> 

$pdf = \App::make('dompdf.wrapper');
$pdf->loadView('view');

Please or to participate in this conversation.