How to Create PDF Document Using Laravel and DomPDF With Custom Font



Most web applications today require generating pdf document, be it invoices, reports, and so on. 

In this tutorial we are going to make use of Laravel, and a laravel library Laravel Dompdf.


Installation

Install the library using composer 


composer require barryvdh/laravel-dompdf

Add the ServiceProvider to the providers array in config/app.php

Barryvdh\DomPDF\ServiceProvider::class,

You can optionally use the facade for shorter code. Add this to your facades:

'PDF' => Barryvdh\DomPDF\Facade::class,

Usage

create a folder called 'pdf' in view folder, then create a blade file in it, call it invoice.blade.php

$pdf = PDF::loadView('pdf.invoice');
return $pdf->stream('invoice.pdf');

- First line load your view folder you created earlier

- Second line display the pdf document in browser, if you want to download it directly, just use download instead of stream

Using Custom Font

Custom font, i mean using external font. If you just add font like regular html document it won't work.

The library comes with different fonts like Helvetica and so on, but you can also use your font you download be it .ttf, .woff or any font format.

- Create a  fonts folder in storage folder, like so:


- Downlod load_font.php file

- Download your desired font, we are using Open_Sans_Condensed

- Unzip the content, and let use OpenSansCondensed-Light.ttf

- Copy the load_font.php and OpenSansCondensed-Light.ttf you download to your root folder, like so:


- open the load_font.php, then change

$fontDir = "lib/fonts";

to 

$fontDir = "storage/fonts";

- in your terminal, run 

php load_font.php "OpenSansCondensed-Light" OpenSansCondensed-Light.ttf

- after running that command, you should see these 2 files


- then open the blade file your used for your pdf, and import the font like so: 

@font-face {
font-family: 'Textur';
  src: url({{storage_path('fonts/OpenSansCondensed-Light.ttf')}}) format('truetype');
}


use it like this:

body{
font-family:'OpenSansCondensed-Light', sans-serif;
}


enjoy.