Create new page using dompdf laravel
Here's a step-by-step guide on how to create a new page using DomPDF in Laravel:
Step 1: Install DomPDF
First, you need to install DomPDF in your Laravel project. Run the following command in your terminal:
composer require barryvdh/laravel-dompdf
Step 2: Create a new controller
Create a new controller in the app/Http/Controllers
directory. For example, let's create a PdfController.php
file:
// app/Http/Controllers/PdfController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use PDF;
class PdfController extends Controller
{
public function generatePdf()
{
// Your code to generate the PDF goes here
}
}
Step 3: Create a new view
Create a new view in the resources/views
directory. For example, let's create a pdf.blade.php
file:
<!-- resources/views/pdf.blade.php -->
<h1>Welcome to our PDF page!</h1>
<p>This is a sample PDF page.</p>
Step 4: Use DomPDF to generate the PDF
In your PdfController
, use the PDF
facade to generate the PDF:
// app/Http/Controllers/PdfController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use PDF;
class PdfController extends Controller
{
public function generatePdf()
{
$pdf = PDF::loadView('pdf');
return $pdf->download('sample_pdf.pdf');
}
}
In this example, we're using the loadView
method to load the pdf.blade.php
view and generate the PDF. We're then using the download
method to download the PDF file.
Step 5: Route the PDF controller
Add a new route to your routes/web.php
file to route the PDF controller:
// routes/web.php
Route::get('/pdf', 'PdfController@generatePdf');
Step 6: Test the PDF generation
Open your browser and navigate to http://yourdomain.com/pdf
. You should see a prompt to download the PDF file.
That's it! You've successfully created a new page using DomPDF in Laravel.
Note: Make sure to adjust the path to your view file and the PDF file name in the generatePdf
method according to your project's requirements.