I’m having trouble getting mPDF to properly render Farsi (Persian) text using custom fonts like BMitra and IRANSans.
Problem:
The main issue is that when I try to generate a PDF with Farsi content, mPDF either fails to load the specified font, or the text appears in a different font altogether. Additionally, I tried enabling OpenType Layout (OTL) features like useOTL
and useKashida
, but I received an error stating that my font does not support OTL tables:
I attempted using the IRANSans font, but the issue persisted. Here is the relevant part of my PHP code:
$mpdf = new MpdfMpdf([
'fontDir' => array_merge($fontDirs, [__DIR__]),
'format' => $PAGE_FORMAT,
'autoLangToFont' => true,
'mode' => 'utf-8',
'useSubstitutions' => true,
'fontdata' => $fontData +
[
'bmitra' => [
'R' => 'assets/fonts/pdf/bmitra.ttf',
'B' => 'assets/fonts/pdf/bmitrabd.ttf',
],
'btitr' => [
'R' => 'assets/fonts/pdf/btitr.ttf',
'B' => 'assets/fonts/pdf/btitr.ttf'
],
'iransans' => [
'R' => 'assets/fonts/pdf/iransans.ttf',
'B' => 'assets/fonts/pdf/iransans.ttf'
],
'vazir' => [
'R' => 'assets/fonts/pdf/vazir.ttf',
],
],
'default_font' => 'bmitra',
]);
$mpdf->SetDirectionality('rtl');
$imagePath = ($draftArray['imageId'] == 1) ? 'assets/media/backgrounds/A4.min.png' : 'assets/media/backgrounds/A5.min.jpg';
$mpdf->AddPage();
$mpdf->Image($imagePath, 0, 0, $mpdf->w, $mpdf->h, '', '', '', false, 300, '', false);
$headerNumber = '<div dir="rtl" style="text-align: left;">';
$headerNumber .= '<span style="font-family: iransans;">شماره: 123456</span><br>';
$headerNumber .= '<span style="font-family: iransans;">تاریخ: 123456</span><br>';
$headerNumber .= '<span style="font-family: iransans;">پیوست: دارد</span>';
$headerNumber .= '</div>';
$mpdf->WriteHTML($headerNumber, MpdfHTMLParserMode::HTML_BODY);
Setting default_font to BMitra and IRANSans: The text appears, but the font is not correctly applied.
Disabling OTL and Kashida: The font loads, but the text doesn’t render properly (e.g., letters are disconnected or appear in the wrong format).
Using other fonts: I tried different Persian fonts like Vazir and Sahel, but encountered similar issues.
Testing paths and font file validity: The fonts are correctly located and functional.