Search code examples
phppdf-generationfpdf

PHP FPDF Arabic Text Isolated


I am trying to generate a pdf document in the Arabic language, I have the same in English format using fpdf. After doing some research, I ended up replacing fpdf with tfpdf and tcpdf. The later messed up my pdf layout and did not work 100% with arabic words. So I opted for tfpdf.

After more research of tfpdf I ended up with the following code:

//to add custom font from unicode folder
$pdf->AddFont('Tajawal', '', 'Tajawal-Medium.ttf', true); 
//to set the custom font 
$pdf->SetFont('Tajawal','',18,true);
    
//helper function to rever the arabic string since I get the output reversed in the pdf
function utf8_strrev($str){
    preg_match_all('/./us', $str, $ar);
    return implode(array_reverse($ar[0]));
}
//$answer comes from a php and is an arabic string        
$pdf->MultiCell(0 , 7, utf8_strrev($answer),1); 

enter image description here

As depicted in the picture (screenshot from generated pdf), the Arabic letters are separated/disjoint but have a correct order thanks to the reverse helper function. How can we fix this issue in tfpdf?

Additional Information

The font I used is Tajawal, it's an Arabic google font: https://fonts.google.com/specimen/Tajawal?subset=arabic

I have added these to my html document:

ini_set('default_charset', 'UTF-8');
<html dir="rtl" lang="ar">
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">

I also tried inserting the same Arabic fields in a database and they work perfectly.


Solution

  • After trying for a while, I found out that the best solution is to use TCPDF for laravel instead of FPDF. You can build your code starting with this small example:

    $html_content = '<h1 dir="rtl">يسبي</h1>';
    PDF::SetTitle('Sample PDF');
    PDF::SetFont('aealarabiya', '', 18);
    PDF::AddPage();
    PDF::writeHTML($html_content, true, false, true, false, '');
    PDF::Output('SamplePDF.pdf');
    

    You can also check this link for more details on the TCPDF library for arabic pdf generation.