How to generate a PDF in laravel | TCPDF in laravel

Use composer:

 composer require elibyy/tcpdf-laravel

Or use package

Requirements

To use TCPDF in Laravel, we are going to include the tcpdf-laravel package in our project. You can add the package to your project adding the following line in your composer.json file :

 {
    “require”: {
        “elibyy/tcpdf-laravel”: “5.2.*”
    }
}

Implementation

Now that the library is included in your project, you need to enable it in your service provider.

Go to your app.php file (yourapp/config/app.php) and add the Laravel TCPDF service provider :

‘providers’ => [
    //…
    ElibyyTCPDFServiceProvider::class,
]

Using TCPDF with an alias
You can define an alias (whatever you want) for TCPDF to prevent the direct declaration of a new class element and use the TCPDF::Method syntax without instantiation.

Go to your app.php file (yourapp/config/app.php) and add the alias for the class :

‘aliases’ => [
    //…
    ‘PDF’ => ElibyyTCPDFFacadesTCPDF::class
]

Now, TCPDF has an alias as PDF and you’ll be able to generate PDF’s in your controller using :

<?php
namespace AppHttpControllers;
use AppHttpControllersController;
use PDF;
class DefaultController extends Controller
{
    public function index()
    {
        $html = ‘<h1>Hello World</h1>’;
     
        PDF::SetTitle(‘Hello World’);
        PDF::AddPage();
        PDF::writeHTML($html, true, false, true, false, ”);
        PDF::Output(‘hello_world.pdf’);
    }
}

Is a good practice to handle the HTML content in a view instead of manipulate it manually in the controller.

You can draw your PDF content as html in a template, retrieve the html generated by the view and write into the PDF :

<?php
namespace AppHttpControllers;
use AppHttpControllersController;
use ElibyyTCPDFFacadesTCPDF;
class DefaultController extends Controller
{
    public function index()
    {
        $view = View::make(‘myview_name’);
        $html = $view->render();
     
        $pdf = new TCPDF();
        $pdf::SetTitle(‘Hello World’);
        $pdf::AddPage();
        $pdf::writeHTML($html, true, false, true, false, ”);
        $pdf::Output(‘hello_world.pdf’);
    }
}

Leave a Reply