Generating a PDF file from a view in Laravel is a common requirement for creating printable documents or reports. Here's how you can achieve this using the "dompdf" package:
Step 1: Install dompdf Package
In your terminal, run the following command to install the "dompdf" package:
composer require barryvdh/laravel-dompdf
Step 2: Create a PDF View
Create a Blade view that represents the content you want to include in the PDF. For example, you can create a file named `pdf.blade.php` in the `resources/views` directory.
Step 3: Generate the PDF
In your controller, you can use the `PDF` facade from the "dompdf" package to generate the PDF from the view. Here's an example:
use PDF;
public function generatePDF()
{
$data = ['title' => 'Sample PDF'];
$pdf = PDF::loadView('pdf', $data);
return $pdf->download('sample.pdf');
}
In this example, the `generatePDF` method loads the `pdf` view with the provided data and then uses the `download` method to generate and download the PDF file named "sample.pdf".
Step 4: Define a Route
Define a route to access the `generatePDF` method. Open your `routes/web.php` file and add the following route:
Route::get('generate-pdf', 'PDFController@generatePDF');
Step 5: Create a View
Create a view named `pdf.blade.php` in the `resources/views` directory. This view will represent the content you want to include in the PDF. For example:
<!DOCTYPE html>
<html>
<head>
<title>{{ $title }}</title>
</head>
<body>
<h1>{{ $title }}</h1>
<p>This is a sample PDF generated from a view in Laravel.</p>
</body>
</html>
Step 6: Access the Route
Access the route you defined in Step 4, such as `http://your-app-url/generate-pdf`, to generate and download the PDF file.
By following these steps, you can generate a PDF file from a view in Laravel using the "dompdf" package. This approach is useful for creating various types of PDF documents within your Laravel application.
0 Comments