Laravel TCPDF: Generate HTML to PDF File Example

By Hardik Savani April 16, 2024 Category : Laravel

Hey Dev,

In this tute, we will discuss laravel tcpdf example. We will look at an example of how to integrate tcpdf in laravel. This tutorial will give you a simple example of how to use tcpdf in laravel. I would like to show you laravel tcpdf generate pdf file.

You can use this example with laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 versions.

We will use elibyy/tcpdf-laravel composer package to generate a pdf file in laravel. we will use SetTitle(), AddPage(), writeHTML() and Output() method to create pdf file in laravel tcpdf. so let's follow the below steps:

Step 1 : Install Laravel

first of all, we need to get 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 Package

here, we will install elibyy/tcpdf-laravel package for create pdf file in laravel. so, let's run the bellow commands:

composer require elibyy/tcpdf-laravel

Step 3: Create Route

In this is step we need to create one route for generate pdf using tcpdf in laravel. let's add the below route on web.php file.



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 index()method.

Add the below code on controller file.



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 -!'


$html = view()->make('pdfSample', $data)->render();

$pdf = new TCPDF;

$pdf::SetTitle('Hello World');


$pdf::writeHTML($html, true, false, true, false, '');

$pdf::Output(public_path($filename), 'F');

return response()->download(public_path($filename));



Step 5: Create Blade File

we will create pdfSample.blade.php file to generate html to pdf file. so let's create following blade file.


<!DOCTYPE html>



<title>Generate PDF using Laravel TCPDF -</title>



<h1 style="color:red;">{!! $title !!}</h1>


<p>Your message here.</p>



Run Laravel App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:

php artisan serve

Now, Go to your web browser, type the given URL and view the app output:



I hope it can help you...

Tags :