Based on @hrvoje-golcic answer, here's an improved and less dirty way to add fonts to mPDF without editing config_fonts.php
. I'm using Laravel, I installed mPDF using composer.
- As suggested by the author, define a constant named
_MPDF_TTFONTPATH
before initializing mPDF
with the value as the path to your ttfonts
folder (this constant exists since at least 5.3).
- Copy the
vendor/mpdf/mpdf/ttfonts
folder to a location that you control (outside of the vendor folder).
- Add your custom fonts to that folder along with the others.
- Add your configuration to the
fontdata
property on the mPDF
instance.
Heads up: The ttfonts
folder has around 90MB so there's still might be a better way, but you have to copy all the fonts since the original config adds them. See composer script alternative at the bottom of this answer.
IMPORTANT: CSS font-family will be transformed to lowercase + nospaces so "Source Sans Pro" will become sourcesanspro.
Here's an example:
if (!defined('_MPDF_TTFONTPATH')) {
// an absolute path is preferred, trailing slash required:
define('_MPDF_TTFONTPATH', realpath('fonts/'));
// example using Laravel's resource_path function:
// define('_MPDF_TTFONTPATH', resource_path('fonts/'));
}
function add_custom_fonts_to_mpdf($mpdf, $fonts_list) {
$fontdata = [
'sourcesanspro' => [
'R' => 'SourceSansPro-Regular.ttf',
'B' => 'SourceSansPro-Bold.ttf',
],
];
foreach ($fontdata as $f => $fs) {
// add to fontdata array
$mpdf->fontdata[$f] = $fs;
// add to available fonts array
foreach (['R', 'B', 'I', 'BI'] as $style) {
if (isset($fs[$style]) && $fs[$style]) {
// warning: no suffix for regular style! hours wasted: 2
$mpdf->available_unifonts[] = $f . trim($style, 'R');
}
}
}
$mpdf->default_available_fonts = $mpdf->available_unifonts;
}
$mpdf = new mPDF('UTF-8', 'A4');
add_custom_fonts_to_mpdf($mpdf);
$mpdf->WriteHTML($html);
Composer post-install script
Instead of copying all the fonts and adding them to git, a handy workaround using a composer post-install script can do that for you.
First of all, make sure the folder where you wish to copy the fonts exists, and create a .gitignore
in it, with the following contents:
*
!.gitignore
!SourceSansPro-Regular.ttf
!SourceSansPro-Bold.ttf
This will ignore everything except the .gitignore
file and the fonts you wish to add.
Next, add the following scripts to your composer.json
file:
"scripts": {
"post-install-cmd": [
"cp -f vendor/mpdf/mpdf/ttfonts/* resources/fonts/"
],
"post-update-cmd": [
"cp -f vendor/mpdf/mpdf/ttfonts/* resources/fonts/"
]
}
Notes
This was tested to work with 6.1.
In 7.x, the author implemented an elegant way to add external fonts.