Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to generate PDF file and add TrueType fonts using PHP ?

  • Last Updated : 24 Aug, 2021

In this article, we will learn how to generate PDF files and add new TrueType fonts with PHP by using FPDF. It is a free PHP class that contains many functions for creating and modifying PDFs. The FPDF class includes many features like page formats, page headers, footers, automatic page break, line break, image support, colors, links, and many more.

Approach:

  • Step 1: You need to download the FPDF class from the FPDF website and include it in your PHP script.
    require('fpdf/fpdf.php');
  • Step 2: Add the following files into your codes for using TrueType or Type1 fonts so that you are not limited to the standard fonts.
    define('FPDF_FONTPATH','./');
  • Step 3: Instantiate and use the FPDF class according to your need as shown in the following example.
    $pdf=new FPDF();

Note: After downloading the FPDF class, make sure that the files “calligra.z” and “calligra.php” are in the same working directory where the PHP code is placed for generating the PDF file.

 



Example: The following example generates a PDF file with new calligraphy or fonts. The file can be downloaded or previewed as needed.

PHP




<?php
  define('FPDF_FONTPATH','./');
  
  require('fpdf/fpdf.php');
  
  $pdf=new FPDF();
  
  // Add new font from the calligra.php file
  $pdf->AddFont('Calligrapher','','calligra.php');
  
  //Add a new page
  $pdf->AddPage();
  
  // Set the font for the text
  $pdf->SetFont('Calligrapher','',35);
  
  // Prints a cell with given text 
  $pdf->Cell(60,20,'Hello GeeksforGeeks!');
  
  // Set the font for the text
  $pdf->SetFont('Calligrapher','',72);
  
  // Prints a cell with given text 
  $pdf->Cell(60,60,'Its fun');
  
  // return the generated output
  $pdf->Output();
?>

Output:

Add Calligraphy font

Advantage of using a new font in PDF: The advantage is that the PDF file is lighter. If the standard font is not available, a substitution font is used. It is always preferable to ensure that the required font is installed on the client systems. If the file is to be viewed by many people or a large audience, it is better to embed it.

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!