Genreate a pdf using Laravel 5

In this tutorial i will show you how to export pdf or download using maatwebsite package. maatwebsite is a package which is used to genreate pdf file.you have a list of items in tables data you can download it in pdf formate.So lets start how to export or genreate a pdf.

Laravel 5 PDF


Step 1 : Add a new package in your composer.json file.


"maatwebsite/excel": "~2.1.0"

Then, run command composer update.

Step 2 : Now open config/app.php file and add service provider and aliase.


'providers' => [
 'Maatwebsite\Excel\ExcelServiceProvider',
],
'aliases' => [
 'Excel' => 'Maatwebsite\Excel\Facades\Excel',
],

Then run this command and this command is genreate config file for excel package.


php artisan vendor:publish

Step 3 : Also add dompdf package to download the pdf format.


composer require dompdf/dompdf

Step 4 : You have to create some migration command.


php artisan make:migration create_items_table

After this command you will find a file in path database/migrations and add this code to your migration file.


<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateItemsTable extends Migration
{
   public function up()
   {
       Schema::create('items', function (Blueprint $table) {
           $table->increments('id');
           $table->string('title');
           $table->text('description');
           $table->timestamps();
       });
   }
   public function down()
   {
       Schema::drop("items");
   }
}

After creating the item table now you need to create a model in app/Item.php .


<?php

namespace App;
use Illuminate\Database\Eloquent\Model;
class Item extends Model
{
   public $fillable = ['title','description'];
}

Step 5 :  Create Route and Controller in your app/Http/routes.php file.


Route::get('genreatepdf', 'ExportController@export');

Create a controller in path app/Http/Controllers/ExportController.php and put the below code.


<?php

use Input;
use App\Item;
use Excel;
class ExportController extends Controller
{
 public function export()
 {
    $data = Item::get()->toArray();
    return Excel::create('wantcode', function($excel) use ($data) {
  $excel->sheet('sheet1', function($sheet) use ($data)
     {
   $sheet->fromArray($data);
     });
    })->download("pdf");
 }
}

In this controller you just simply get the items array and pass to the excel function and download as PDF.

No comments:

Post a Comment

Download the eBook of react js for beginners

ReactJS basically is an open-source JavaScript library which is used for building user interfaces specifically for single page applications...

Popular