Laravel Dompdf Set Different font-family Example

Admin   Laravel   886  2021-03-15 15:20:07

In tis example I will explain you to Dompdf Set Different font-family Example in laravel/php.When generating a PDF with Dompdf then it ignores fonts that are not available in its internally – Helvetica, Times-Roman, Courier, Zapf-Dingbats, Symbol.

Require to load the fonts for use in PDF creation which is not existing in Dompdf internal fonts.

In this tutorial, I am creating PDF of MySQL database table records and set its font-family using Dompdf.

Step 1: Download Dompdf

Download Dompdf latest version from here.

Copy and extract it in your project directory.

Step 2 :Table structure

Create users table and add some records.

 

CREATE TABLE `users` (

`id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,

`username` varchar(100) NOT NULL,

`name` varchar(100) NOT NULL,

`email` varchar(100) NOT NULL

) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Step 3: Configuration

Create a config.php for the database connection.

 

<?php

$host = "localhost"; /* Host name */

$user = "root"; /* User */

$password = ""; /* Password */

$dbname = "tutorial"; /* Database name */

$con = mysqli_connect($host, $user, $password,$dbname);

// Check connection

if (!$con) {

die("Connection failed: " . mysqli_connect_error());

}

Step 4: Copy fonts

Create a new fonts folder at the project root.

Copy your fonts which you want to use in your pdf to the fonts folder. I have copied OpenSans-Regular.ttf and OpenSans-Bold.ttf to the folder.

Step 5 :Create PDF and set font-family

In this step create Create a new pdf.php file.

Load Fonts and Use it

Create $html variable to store data in HTML format for pdf generation.

Load fonts using @font-face CSS rule.

In the example, I am loading OpenSans-Regular and OpenSans-Bold fonts.

Pass the file path in src.

Now, use these fonts in the selectors.

I used 'OpenSans-Bold' in header columns and 'OpenSans-Regular' in body columns.

Add data and create PDF

Fetch all records from the users table and create new rows.

Create an object of Dompdf and pass $html in loadHtml() method.

Completed Code