php - adding font to mPDF -
i'm getting following error when try , generate pdf using mpdf class:
ttf file "c:/wamp/www/inc/mpdf/ttfonts/verdana.ttf": invalid checksum 20f65173c11 table: dsig (expected 65173c11)
i've uploaded font files ttfonts
directory , defined font in config_fonts.php
this:
"verdana" => array( 'r' => "verdana.ttf", 'b' => "verdanab.ttf", 'i' => "verdanai.ttf", 'bi' => "verdanaz.ttf", ),
i see error when turn on font error reporting in config settings. when turn error reporting off, pdf generated, font being used not verdana.
any idea on i'm doing wrong?
based on @hrvoje-golcic answer, here's improved , less dirty way add fonts mpdf without editing config_fonts.php
. i'm using laravel, installed mpdf using composer.
- as suggested author, define constant named
_mpdf_ttfontpath
before initializingmpdf
value pathttfonts
folder (this constant exists since @ least 5.3). - copy
vendor/mpdf/mpdf/ttfonts
folder location control (outside of vendor folder). - add custom fonts folder along others.
- add configuration
fontdata
property onmpdf
instance.
heads up:
ttfonts
folder has around 90mb there's still might better way, have copy fonts since original config adds them. see composer script alternative @ bottom of answer.important: css font-family transformed lowercase + nospaces "source sans pro" become sourcesanspro.
here's example:
if (!defined('_mpdf_ttfontpath')) { // absolute path 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 $f => $fs) { // add fontdata array $mpdf->fontdata[$f] = $fs; // add available fonts array foreach (['r', 'b', 'i', 'bi'] $style) { if (isset($fs[$style]) && $fs[$style]) { // warning: no suffix 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 fonts , adding them git, handy workaround using composer post-install script can you.
first of all, make sure folder wish copy fonts exists, , create .gitignore
in it, following contents:
* !.gitignore !sourcesanspro-regular.ttf !sourcesanspro-bold.ttf
this ignore except .gitignore
file , fonts wish add.
next, add following scripts 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 tested work 6.1.
in 7.x, author implemented elegant way add external fonts.
Comments
Post a Comment