Learn how to generate and download PDF files using Laravel and Vue.js 3. Step-by-step guide with API integration, Axios blob handling, DOMPDF setup, and best practices for secure, fast PDF exports.
composer require barryvdh/laravel-dompdf
php artisan make:controller Api/PdfController
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Barryvdh\DomPDF\Facade\Pdf;
class PdfController extends Controller
{
public function download()
{
$data = [
'title' => 'Invoice Report',
'date' => now()->format('d M Y'),
'items' => [
['name' => 'Web Development', 'price' => 5000],
['name' => 'Hosting Service', 'price' => 1500],
]
];
$pdf = Pdf::loadView('pdf.invoice', $data);
return $pdf->download('invoice.pdf');
}
}
resources/views/pdf/invoice.blade.php
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: DejaVu Sans; }
table { width: 100%; border-collapse: collapse; }
th, td { border: 1px solid #ddd; padding: 8px; }
th { background: #f3f4f6; }
</style>
</head>
<body>
<h2>{{ $title }}</h2>
<p>Date: {{ $date }}</p>
<table>
<thead>
<tr>
<th>Item</th>
<th>Price (৳)</th>
</tr>
</thead>
<tbody>
@foreach($items as $item)
<tr>
<td>{{ $item['name'] }}</td>
<td>{{ $item['price'] }}</td>
</tr>
@endforeach
</tbody>
</table>
</body>
</html>
routes/api.php
use App\Http\Controllers\Api\PdfController;
Route::get('/download-pdf', [PdfController::class, 'download']);
import axios from 'axios'
const downloadPdf = async () => {
const response = await axios.get(
'http://your-domain.test/api/download-pdf',
{ responseType: 'blob' }
)
const blob = new Blob([response.data], { type: 'application/pdf' })
const url = window.URL.createObjectURL(blob)
const link = document.createElement('a')
link.href = url
link.download = 'invoice.pdf'
link.click()
window.URL.revokeObjectURL(url)
}
<button @click="downloadPdf" class="px-4 py-2 bg-indigo-600 text-white rounded" > Download PDF </button>