If you are developing a PHP based web application using Laravel and have some requirement to create PDF documents then you have very limited choice. I was searching some php library for generating PDF document and came across Dompdf. It’s a very simple Laravel library which can be used for generating PDF with lots of Options. You can create single or multiple PDF with page size, page orientation and can show / download PDF or return it as String.
First step is to download the Dompdf library. To download the project use one of the two approaches below.
1) Run the following command on your projects base directory.
1
|
composer require thujohn/pdf
|
I ran the above command and got the following output.
2) Edit composer.js file, add thujohn/pdf entry and run composer update
to pull down the latest version of Pdf..
1
|
“thujohn/pdf”: “dev-master”
|
Following is my composer.js file I am sharing for your reference.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
{
“name”: “laravel/laravel”,
“description”: “The Laravel Framework.”,
“keywords”: [“framework”, “laravel”],
“license”: “MIT”,
“require”: {
“laravel/framework”: “4.2.*”,
“thujohn/pdf”: “1.0.6”
},
“autoload”: {
“classmap”: [
“app/commands”,
“app/controllers”,
“app/models”,
“app/database/migrations”,
“app/database/seeds”,
“app/tests/TestCase.php”
]
},
“scripts”: {
“post-install-cmd”: [
“php artisan clear-compiled”,
“php artisan optimize”
],
“post-update-cmd”: [
“php artisan clear-compiled”,
“php artisan optimize”
],
“post-create-project-cmd”: [
“php artisan key:generate”
]
},
“repositories”: {
“packagist”: { “url”: “https://packagist.org”, “type”: “composer” }
},
“config”: {
“preferred-install”: “dist”
},
“minimum-stability”: “stable”,
“thujohn/pdf”: “dev-master”
}
|
Second step is to open app.php file available in /app/config/app.php
directory and add a new entry in providers array.
1
2
3
4
5
|
‘providers’ => array(
‘Illuminate\Foundation\Providers\ArtisanServiceProvider’,
......
‘Thujohn\Pdf\PdfServiceProvider’,
)
|
Now add the alias.
1
2
3
|
‘aliases’ => array(
‘PDF’ => ‘Thujohn\Pdf\PdfFacade’,
)
|
To test your PDF document, add following code in route.php
1
2
3
4
5
6
7
|
Route::get(‘/pdf’, function()
{
$html = ‘‘
. ‘
Hello, Welcome to TechZoo. ‘ . ‘‘;
return PDF::load($html, ‘A4’, ‘portrait’)->download(‘my_pdf’);
});
|
Now, we are all set. Open the browser and hit the URL you will see following Output.
Happy Coding 🙂
Source techzoo.org