How to Set Up External Fonts in TCPDF

Environment
- PHP 8.2
- Laravel 9
- docker-compose
- Running on AWS cloud with docker platform
Issue Description
I'm developing a feature that uses TCPDF (+ FPDI) to write text on an existing PDF template. Since the template uses MS Mincho font, I wrote the following code to match it:
$pdf = new Fpdi();
~~~
$tcpdfFonts = new TCPDF_FONTS();
$font = $tcpdfFonts->addTTFfont(resource_path('msmincho.ttf'));
$pdf->SetFont($font, '', 12);
This worked fine on my local environment, but when deployed to AWS cloud, I got the following error:
ErrorException: fopen(file:///var/www/app/vendor/tecnickcom/tcpdf/fonts/msmincho.z): Failed to open stream: Permission denied in /var/www/app/vendor/tecnickcom/tcpdf/include/tcpdf_static.php:1839
Could you please advise how to resolve this error?
Answer
I found the solution myself, so I'm sharing it here.
The issue was that font files were being generated in the vendor
directory under the TCPDF package, so I addressed this problem.
Read more
$tcpdfFonts->addTTFfont(
fontfile: resource_path('fonts/msmincho.ttf'),
// Create the storage/app/tcpdf/fonts directory beforehand
outpath: storage_path('app/tcpdf/fonts/')
);
This resolved the original error log message, but then I encountered the following error:
<strong>TCPDF ERROR: </strong>Could not include font definition file: msmincho
It was necessary to load the generated font file with TCPDF::SetFont()
. After reading the package source code, I finally modified the code as follows, which now works correctly:
https://tcpdf.org/docs/srcdoc/TCPDF/classes-TCPDF/#method_setFont
$fontName = 'msmincho';
$fontDir = storage_path('app/tcpdf/fonts/');
$tcpdfFonts = new TCPDF_FONTS();
$font = $tcpdfFonts->addTTFfont(
fontfile: resource_path("fonts/{$fontName}.ttf"),
outpath: $fontDir,
);
$this->pdf->SetFont(
family: $font,
size: 12,
fontfile: "{$fontDir}/{$fontName}.php"
);
I'm also including a related answer that might be helpful:
TCPDF, "Could not include font definition file" with OpenType fonts
I hope this helps anyone facing similar issues with TCPDF font permissions in Docker/cloud environments!
Enjoyed this article?
Check out more content on our blog or follow us on social media.
Browse more articles