How To Add Custom Font in FPDF


In this tutorial shows, how to add custom font in FPDF library.

The FPDF library includes a set of predefined standard fonts only. If we add a custom font to FPDF, we will need to follow these steps:

1.Prepare the Font Files:

We will download the TrueType font file (TTF) for the custom font you want to use.

2. Conter TrueType Font (.ttf) into FPDF Font Library(.php and .z):

FPDF cannot directly utilize fonts from TrueType Font (TTF) files so we convert all the TrueType (TTF) fonts into FPDF font library from this http://www.fpdf.org/makefont/.

When you upload a TrueType Font (TTF) file in http://www.fpdf.org/makefont/ link,It will generate two files as shown in the following image.

Conter TrueType Font (.ttf) into FPDF Font Library(.php and .z):
Conter TrueType Font (.ttf) into FPDF Font Library(.php and .z)

3.Add The Custom Fonts in FPDF Library:

When converting TTF files, we'll obtain PHP and Z files with the same names as the font file.Copy Copy all *.php and *.z Files in FPDF Font folder (fpdf185/font/).

Add The Custom Fonts in FPDF Library

4.Add the font into the documents:

To add a custom font to fpdf documents, use the AddFont method of the fpdf library.

Syntax
<?php
  $pdf->AddFont('font_family','font_style','font_definition_file');
?>

The following example shows, how to add custom font in FPDF.

Example
<?php 
  require('fpdf/fpdf.php');
  
  $pdf = new FPDF();
  $pdf->AddPage();
  
  $pdf->AddFont("PlaypenSans","","PlaypenSans-Regular.php");
  $pdf->AddFont("PlaypenSans","B","PlaypenSans-Bold.php");
  
  $pdf->SetFont("PlaypenSans","",16);
  $pdf->Cell(50,10,"Sample Text");
  
  $pdf->SetFont("PlaypenSans","B",16);
  $pdf->Cell(50,10,"Sample Text");
  
  $pdf->Output();
?>
Output