Laravel add custom font in Mpdf

To add a custom font to Mpdf in Laravel, you can follow these steps:

  1. Download the font files: First, you need to download the font files in the appropriate format. Mpdf supports TrueType and OpenType fonts. You can download the font files from the font's official website or from a font repository like Google Fonts.

  2. Store the font files: Store the font files in your Laravel application's public directory, under a subfolder named "fonts". You can create the "fonts" folder manually or by using Laravel's File facade, like so:

use Illuminate\Support\Facades\File;

File::makeDirectory(public_path('fonts'), $mode = 0777, true, true);


  1. Register the font with Mpdf: In your Laravel application, open the Mpdf configuration file, typically located at config/mpdf.php. In this file, add an entry to the fontdata array that specifies the font's name, the path to the font file, and any other necessary parameters. For example:

'fontdata' => [
'myfont' => [
'R' => 'myfont.ttf',
'B' => 'myfont-bold.ttf',
'I' => 'myfont-italic.ttf',
'BI' => 'myfont-bold-italic.ttf',
'useOTL' => 0xFF,
'useKashida' => 75,
],
],



This code specifies a font named "myfont", with four variants: regular, bold, italic, and bold italic. The font files are stored in the "fonts" directory. The useOTL and useKashida options are optional and control advanced font features.

  1. Use the font in Mpdf: In your Laravel code, when creating an Mpdf object, you can specify the font you want to use by passing its name to the SetFont() method. For example:

$mpdf = new \Mpdf\Mpdf(['mode' => 'utf-8', 'format' => 'A4']);

$mpdf->SetFont('myfont', 'B', 14);



This code creates an Mpdf object with UTF-8 encoding and A4 page size, and sets the font to "myfont" in bold style, with a font size of 14pt.

That's it! With these steps, you can add a custom font to Mpdf in Laravel and use it in your PDF generation code.


No comments:

Post a Comment

how to call ssh from vs code

 To call SSH from VS Code, you can use the built-in Remote Development extension. This extension allows you to open a remote folder or works...