Laravel 4 create PDF (use dompdf)

After not updating this blog for a few days, now I want to share how to create PDF in laravel using dompdf package from https://github.com/barryvdh/laravel-dompdf. Ok for installation follow this steps:
First we must add the barryvdh/laravel-dompdf to the composer with command:

aim@linux-yr22:~$ composer require barryvdh/laravel-dompdf:* --no-update
aim@linux-yr22:~$ composer update

Then we must add service provider to app/config/app.php:

	'providers' => array(

		'Illuminate\Foundation\Providers\ArtisanServiceProvider',
		'Illuminate\Auth\AuthServiceProvider',
		'Illuminate\Cache\CacheServiceProvider',
		'Illuminate\Session\CommandsServiceProvider',
		'Illuminate\Foundation\Providers\ConsoleSupportServiceProvider',
		'Illuminate\Routing\ControllerServiceProvider',
		'Illuminate\Cookie\CookieServiceProvider',
		'Illuminate\Database\DatabaseServiceProvider',
		'Illuminate\Encryption\EncryptionServiceProvider',
		'Illuminate\Filesystem\FilesystemServiceProvider',
		'Illuminate\Hashing\HashServiceProvider',
		'Illuminate\Html\HtmlServiceProvider',
		'Illuminate\Log\LogServiceProvider',
		'Illuminate\Mail\MailServiceProvider',
		'Illuminate\Database\MigrationServiceProvider',
		'Illuminate\Pagination\PaginationServiceProvider',
		'Illuminate\Queue\QueueServiceProvider',
		'Illuminate\Redis\RedisServiceProvider',
		'Illuminate\Remote\RemoteServiceProvider',
		'Illuminate\Auth\Reminders\ReminderServiceProvider',
		'Illuminate\Database\SeedServiceProvider',
		'Illuminate\Session\SessionServiceProvider',
		'Illuminate\Translation\TranslationServiceProvider',
		'Illuminate\Validation\ValidationServiceProvider',
		'Illuminate\View\ViewServiceProvider',
		'Illuminate\Workbench\WorkbenchServiceProvider',
		'Barryvdh\Debugbar\ServiceProvider',
		'Barryvdh\DomPDF\ServiceProvider',
	),

Then add Facade for shorter code. What facade? I will explain later in below paragraph.

	'aliases' => array(

		'App'             => 'Illuminate\Support\Facades\App',
		'Artisan'         => 'Illuminate\Support\Facades\Artisan',
		'Auth'            => 'Illuminate\Support\Facades\Auth',
		'Blade'           => 'Illuminate\Support\Facades\Blade',
		'Cache'           => 'Illuminate\Support\Facades\Cache',
		'ClassLoader'     => 'Illuminate\Support\ClassLoader',
		'Config'          => 'Illuminate\Support\Facades\Config',
		'Controller'      => 'Illuminate\Routing\Controller',
		'Cookie'          => 'Illuminate\Support\Facades\Cookie',
		'Crypt'           => 'Illuminate\Support\Facades\Crypt',
		'DB'              => 'Illuminate\Support\Facades\DB',
		'Eloquent'        => 'Illuminate\Database\Eloquent\Model',
		'Event'           => 'Illuminate\Support\Facades\Event',
		'File'            => 'Illuminate\Support\Facades\File',
		'Form'            => 'Illuminate\Support\Facades\Form',
		'Hash'            => 'Illuminate\Support\Facades\Hash',
		'HTML'            => 'Illuminate\Support\Facades\HTML',
		'Input'           => 'Illuminate\Support\Facades\Input',
		'Lang'            => 'Illuminate\Support\Facades\Lang',
		'Log'             => 'Illuminate\Support\Facades\Log',
		'Mail'            => 'Illuminate\Support\Facades\Mail',
		'Paginator'       => 'Illuminate\Support\Facades\Paginator',
		'Password'        => 'Illuminate\Support\Facades\Password',
		'Queue'           => 'Illuminate\Support\Facades\Queue',
		'Redirect'        => 'Illuminate\Support\Facades\Redirect',
		'Redis'           => 'Illuminate\Support\Facades\Redis',
		'Request'         => 'Illuminate\Support\Facades\Request',
		'Response'        => 'Illuminate\Support\Facades\Response',
		'Route'           => 'Illuminate\Support\Facades\Route',
		'Schema'          => 'Illuminate\Support\Facades\Schema',
		'Seeder'          => 'Illuminate\Database\Seeder',
		'Session'         => 'Illuminate\Support\Facades\Session',
		'SSH'             => 'Illuminate\Support\Facades\SSH',
		'Str'             => 'Illuminate\Support\Str',
		'URL'             => 'Illuminate\Support\Facades\URL',
		'Validator'       => 'Illuminate\Support\Facades\Validator',
		'View'            => 'Illuminate\Support\Facades\View',
		'PDF' 			  => 'Barryvdh\DomPDF\Facade',

	),

And now open your laravel controller and add file PrintController.php:

<?php
class PrintController extends \BaseController 
{
	public function index()
	{
		$pdf = App::make('dompdf');
		$pdf->loadHTML('<h1>Hello World!!</h1>');
		return $pdf->stream();
	}
}

Then change the route to be like this:

<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the Closure to execute when that URI is requested.
|
*/

Route::get('/', 'PrintController@index');

And then run this laravel on your browser. If your code not wrong, you can get result like this:

And if we want use Facade, so we mush change the PrintController.php like this:

<?php
class PrintController extends \BaseController 
{
	public function index()
	{
		$pdf = PDF::loadHTML('<h1>Hello World!!</h1>');
		return $pdf->stream();
	}
}

So if we run this code, we can get same result from the above picture. But what different with Facade and no?

If we using facade, so the code can be shorter than if we not use facade code.

Ok we’ve made ​​a simple example create PDF using laravel.
May be you have question for me

How to create pdf from external view (from views folder)?

The answer is simple. Now create example view on views folder with name PrintView.php with code like this:

<!DOCTYPE html>
<html>
<head>
	<title>Example</title>
</head>
<body>
	<h1>Hello World!!</h1>
</body>
</html>

So we must change PrintController again to be like this:

<?php
class PrintController extends \BaseController 
{
	public function index()
	{
		$pdf = PDF::loadView('PrintView');
		return $pdf->stream();
	}
}

Now run your laravel and you can get result same on above picture.

And how about add parameter to view?

This is easy to add, you must change little code from PrintView.php and PrintController.php like this:

<!DOCTYPE html>
<html>
<head>
	<title>Example</title>
</head>
<body>
	<h1><?php echo $param ?></h1>
</body>
</html>

So we must change PrintController again to be like this:

<?php
class PrintController extends \BaseController 
{
	public function index()
	{
		$parameterr = array();
		$parameter['param'] = "Hello World!!";

		$pdf = PDF::loadView('PrintView', $parameter);
		return $pdf->stream("Hello.pdf");
	}
}

Now run your laravel and you can get result same on above picture.
The question again.

How if I want to create pdf without the preview page before, but I would like to directly download the message?

For the answer so just change your PrintController.php to be like this:

<?php
class PrintController extends \BaseController 
{
	public function index()
	{
		$pdf = PDF::loadView('PrintView');
		return $pdf->download('test.pdf'); //this code is used for the name pdf
	}
}

Run your laravel again and you can get result like this:

Bonus: you can create custom pdf method using chain code like this:

<?php
class PrintController extends \BaseController 
{
	public function index()
	{
		PDF::loadView('PrintView')->setPaper('a4')->setOrientation('landscape')->setWarnings(false)->save('/home/aim/Documents/test.pdf');

		return "Success";
	}
}

Explanations: from line 6, I create pdf with view from external view (folder views) with paper is “a4” and orientation is landscape with warning is false (not showing) and save the document to “/home/aim/Documents/test.pdf”. The “/home/aim/Documents/test.pdf” is my directory if you’re using Linux OS. So the file is automatic saved and user can open the pdf in directory /home/aim/Documents with name test.pdf.
Source and more info: https://github.com/barryvdh/laravel-dompdf

Advertisements

14 comments

  1. Thanks for tutorial . could you please explain how do we create multi page pdf with passing array to loadView() . for example i have two different addresses in array and i want to print them in same pdf file but in separate pages . Thanks

  2. Currently, I installed dompdf in my windows. If i want it works on the linux server, whether I have to install something on linux server or not, or just upload source code from my local to server and override everything. Sorry i’m new in Laravel.

  3. I have followed this procedure but it show me this Class ‘Barryvdh\Debugbar\ServiceProvider’ not found error .. Any Idea?

  4. Im trying to do this with Laravel 5.

    But I get this error:

    Class ‘BaseController’ not found

    But in my PrintController.php I got this:

    class PrintController extends \BaseController {
    public function index()
    {
    $pdf = App::make(‘dompdf’);
    $pdf->loadHTML(‘

    Hello World!!

    ‘);
    return $pdf->stream();
    }

    1. Hi, If you have add the laravel-dompdf component correctly, here is the code for laravel 5.1

      <?php
      namespace App\Http\Controllers;

      use App\Http\Controllers;
      use View;

      use Barryvdh\DomPDF\Facade as PDF;

      class PrintController extends Controller
      {
      public function index()
      {
      $pdf = \PDF::loadHTML('Hello World!!’);
      return $pdf->stream();
      }
      }

      ?>

      Ps. I know it is a bit late reply, But I hope it will help someone πŸ™‚

  5. This tuto is great but there’s something important to teach, if you generate a pdf from html into a folder, and later you want to check it from a web application, you cannot open it in the browser fine, the browser is displaying rare caracters, but if you open it using Acrobat, no problem but that’s not interesting, can you show us how to open an already generated pdf file in the browser?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s