Hello artisan,
In this tcpdf laravel example tutorial, we will discuss laravel tcpdf example. We will see in this tcpdf laravel 9 tutorial how to integrate tcpdf in laravel application. This tutorial will give you a complete step by step example of how to use tcpdf in laravel. I will show you laravel tcpdf generate pdf file.
You can use this example code in your laravel 6, laravel 7, laravel 8 and laravel 9 versions. We will use elibyy/tcpdf-laravel
composer package to generate a pdf file in laravel. I will use SetTitle(), AddPage(), writeHTML(), and Output() methods to create a pdf file in laravel tcpdf. So let's follow the below steps to create laravel pdf file tcpdf example:
Step 1 : Install Laravel
First of all, we need a fresh Laravel version application using the bellow command, So open your terminal OR command prompt and run the bellow command:
composer create-project laravel/laravel example-app
Step 2: Install elibyy/tcpdf-laravel
Now, we will install elibyy/tcpdf-laravel
package for creating pdf files in laravel. so, let's run the below commands:
composer require elibyy/tcpdf-laravel
Read also: Laravel 9 Yajra Datatables Export Excel CSV Button Example
Step 3: Create Route
In this step, we need to create one route for generating pdf using tcpdf in laravel. let's add the below route on web.php file.
routes/web.php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PDFController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('pdf', [PDFController::class,'index']);
Step 4: Create Controller
in this step, we need to create PDFController with the index()
method. Add the below code to the controller file.
app/Http/Controllers/PDFController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Elibyy\TCPDF\Facades\TCPDF;
class PDFController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function index(Request $request)
{
$filename = 'demo.pdf';
$data = [
'title' => 'Generate PDF using Laravel TCPDF - codecheef.org!'
];
$html = view()->make('pdfSample', $data)->render();
$pdf = new TCPDF;
$pdf::SetTitle('Hello World');
$pdf::AddPage();
$pdf::writeHTML($html, true, false, true, false, '');
$pdf::Output(public_path($filename), 'F');
return response()->download(public_path($filename));
}
}
Step 5: Create Blade File
Now we will create a pdfSample.blade.php file to generate HTML to pdf file. so let's create the following blade file.
resources/views/pdfSample.blade.php
Now you can test. hope it can help you.
#laravel #laravel-9x