Search code examples
phplaravelpdfdownloadlaravel-livewire

Laravel 8 download PDF with Livewire


On my page I am making an invoice that is fully compatible with Livewire. I use this package: https://github.com/LaravelDaily/laravel-invoices to generate my invoice and everything works fine. But their is one problem I ran into. I can't download my PDF with Livewire.

Here is a basic example to generate a PDF and download it:

public function invoice() 
{
    $customer = new Buyer([
        'name'          => 'John Doe',
        'custom_fields' => [
            'email' => 'test@example.com',
        ],
    ]);

    $item = (new InvoiceItem())->title('Service 1')->pricePerUnit(2);

    $invoice = Invoice::make()
        ->buyer($customer)
        ->discountByPercent(10)
        ->taxRate(15)
        ->shipping(1.99)
        ->addItem($item);

    return $invoice->download();
}

Whenever I click on a button

<a role="button" class="pdf-download cursor-pointer" wire:click="invoice">download</a>

Nothing happens. So the problem is that Livewire doesn't support this download method. And this download method looks like this:

public function download()
{
    $this->render();

    return new Response($this->output, Response::HTTP_OK, [
        'Content-Type'        => 'application/pdf',
        'Content-Disposition' => 'attachment; filename="' . $this->filename . '"',
        'Content-Length'      => strlen($this->output),
    ]);
}

$this->render(); Renders a template in a specific folder

Is their a work around for this? Where I can download my pdf with a template or maybe a different strategy. I allready tried one thing. I stored the invoice into a session, like so:

Session::put('invoice', $invoice);
Session::save();

And in a different controller I have.

if ($invoice = Session::get('invoice')) {
    $invoice->download();
}

But that gives me this error:

serialization of 'closure' is not allowed

And I tried some stuff I found here: https://github.com/livewire/livewire/issues/483 But nothing works. Can someone give me a direction on where to look or how to fix this? Thanks!


Solution

  • return response()->streamDownload(function () use($invoice) {
        echo  $invoice->stream();
    }, 'invoice.pdf');
    
    

    Seems to do the trick.