In the world of web development, generating PDF documents is a functionality that many applications require. Whether for reports, invoices, or other types of documents, having a tool that performs this task efficiently can save you time and effort. This time, we show you how to use DomPDF in Laravel to easily generate PDF files.
DomPDF is a PHP library that allows you to transform HTML and CSS into PDF files. It is especially useful for those working with Laravel, as it integrates easily into this platform. With DomPDF, you can create styled PDF documents that maintain the presentation you have designed in HTML.
Installing DomPDF in a Laravel project is a straightforward process. It is recommended to use Composer, the PHP dependency manager. Follow these simple steps:
composer require barryvdh/laravel-dompdf
php artisan vendor:publish --provider="Barryvdh\DomPDF\ServiceProvider"
Once DomPDF is installed, the next step is to generate a basic PDF. First, you need to create a view containing the HTML you want to convert to PDF. You can do this in the resources/views directory.
Create a file named documento.blade.php with the following content:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Sample PDF</title> <style> body { font-family: DejaVu Sans, sans-serif; } h1 { color: #333; } p { margin: 20px 0; } </style> </head> <body> <h1>PDF Document Title</h1> <p>This is a sample content that will be included in the PDF file.</p> </body> </html>
Now, to generate the PDF, you will need to create a controller. Example controller:
use Illuminate\Support\Facades\Route; use App\Http\Controllers\PDFController; class PDFController extends Controller { public function generarPDF() { $pdf = app('dompdf.wrapper'); $pdf->loadView('documento'); return $pdf->stream('documento.pdf'); } }
Finally, don't forget to define the route in the web.php file to access the generated PDF:
Route::get('/generar-pdf', [PDFController::class, 'generarPDF']);
One of the highlights of DomPDF is the ability to customize the generated PDF. You can add headers, footers, images, and more, using CSS to style your content. Additionally, this library is compatible with many common CSS properties, which makes it easy to create attractive documents.
Generating PDFs in Laravel with DomPDF is a relatively simple process that can add great value to your applications. By following the mentioned steps, you can create styled PDF documents in no time.
I invite you to keep exploring more news and related tutorials on my blog, where you will find useful resources to improve your development skills. Don't miss out!
Page loaded in 22.57 ms