To generate a PDF in Laravel, you can use popular packages like dompdf or snappy. Here, we'll use dompdf as it is straightforward and widely used.
Step-by-Step Guide
- Install the package using Composer:
composer require dompdf/dompdf
- Create a new PDF controller:
php artisan make:controller PdfController
- In the controller, create a method to generate the PDF:
use Dompdf\Dompdf;
public function generatePdf()
{
$dompdf = new Dompdf();
$dompdf->loadHtml('<h1>Hello, world!</h1>');
$dompdf->setPaper('A4', 'landscape');
$dompdf->render();
$dompdf->stream();
}
- Add a route to the controller method:
use App\Http\Controllers\PdfController;
Route::get('/pdf', [PdfController::class, 'generatePdf']);
- Visit the URL in your browser to generate the PDF:
http://your-app-url/pdf
This will generate a PDF with the text "Hello, world!" in landscape orientation. You can customize the HTML content and PDF settings as needed.
Step 7: Test the PDF Generation
Start your Laravel development server:
php artisan serve
Visit http://localhost:8000/generate-pdf
in your browser. A PDF will be generated and downloaded or displayed in the browser based on your choice in the controller.
This basic implementation can be extended with more complex layouts or data.
No comments:
Post a Comment