Charles Smith
Charles Smith

Reputation: 3289

dompdf not downloading PDF from Laravel 8 and a Livewire View

I am using dompdf in my Laravel v8.26.1 app. I am also using Laravel Livewire v1.3.5.

I can get a view to download a pdf outside of Livewire, but can't seem to get it to work inside a Livewire view. I've tried every configuration I could think of, but keep running into road blocks. I am either getting an Undefined variable: workorder error, or no error at all, but also no download.

route

...
Route::livewire('/workorder/{workorder}/print', 'admin.workorders.printer')->name('admin.workorder.print')->layout('layouts.admin');
...

livewire/admin/workorders/print.blade

...
<div>
  <button wire:click="generatePDF({{$workorder->id}})">Create PDF</button>
</div>
...

livewire/admin/workorders/printer.php

...
use Barryvdh\DomPDF\Facade as PDF;
...
public function generatePDF($id)
{
    $record = Workorder::find($id);
    $data = [
        'project_id' => $record->project_id,
        'project_name' => $record->project_name,
        'customer_id' => $record->customer_id,
        'generator_id' => $record->generator_id,
        'workorder_po_number' => $record->workorder_po_number,
        'workorder_number' => $record->workorder_number,
        'prevailing_wage' => $record->prevailing_wage,
    ];
    $pdf = PDF::loadView('livewire.admin.workorders.print', $data);
    return $pdf->download('demo.pdf');
}

Upvotes: 7

Views: 9691

Answers (1)

maximus1127
maximus1127

Reputation: 1036

Here you go, just found this. fixed me right up. The only thing I had to change was in the $viewData variable, i just had to make it an array - ['viewData' => $viewData] and then i could access it in my view.

Here is the code in case that link ever goes down:

$pdfContent = PDF::loadView('view', $viewData)->output();
return response()->streamDownload(
     fn () => print($pdfContent),
     "filename.pdf"
);

Upvotes: 21

Related Questions