简体   繁体   English

将字体添加到mPDF

[英]adding font to mPDF

I'm getting the following error when I try and generate a PDF using the mPDF class: 当我尝试使用mPDF类生成PDF时出现以下错误:

TTF file "C:/wamp/www/inc/mpdf/ttfonts/verdana.ttf": invalid checksum 20f65173c11 table: DSIG (expected 65173c11)

I've uploaded the font files to my ttfonts directory and defined the font in config_fonts.php like this: 我已经将字体文件上传到我的ttfonts目录,并在config_fonts.php定义了这样的字体:

"verdana" => array(
    'R' => "verdana.ttf",
    'B' => "verdanab.ttf",
    'I' => "verdanai.ttf",
    'BI' => "verdanaz.ttf",
    ),

I only see the error when I turn on font error reporting in the config settings. 我在配置设置中打开字体错误报告时只看到错误。 When I turn error reporting off, the PDF is generated, but the font being used is not Verdana. 当我关闭错误报告时,会生成PDF,但使用的字体不是Verdana。

Any idea on what I'm doing wrong? 关于我做错了什么的任何想法?

Based on @hrvoje-golcic answer, here's an improved and less dirty way to add fonts to mPDF without editing config_fonts.php . 根据@ hrvoje-golcic的回答,这里是一种改进的,不那么脏的方法,可以在不编辑config_fonts.php情况下将字体添加到mPDF。 I'm using Laravel, I installed mPDF using composer. 我正在使用Laravel,我使用composer安装了mPDF。

  1. 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). 正如笔者建议,定义一个常量名为_MPDF_TTFONTPATH初始化之前mPDF与价值的路径,你ttfonts文件夹(因为至少5.3这个常数存在)。
  2. Copy the vendor/mpdf/mpdf/ttfonts folder to a location that you control (outside of the vendor folder). vendor/mpdf/mpdf/ttfonts文件夹复制到您控制的位置(在vendor文件夹之外)。
  3. Add your custom fonts to that folder along with the others. 将自定义字体与其他字体一起添加到该文件夹​​。
  4. Add your configuration to the fontdata property on the mPDF instance. 将配置添加到mPDF实例上的fontdata属性。

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. 抬头ttfonts文件夹大约有90MB,所以仍然可能有更好的方法,但是你需要复制所有字体,因为原始配置会添加它们。 See composer script alternative at the bottom of this answer. 请参阅本答案底部的composer script alternative。

IMPORTANT: CSS font-family will be transformed to lowercase + nospaces so "Source Sans Pro" will become sourcesanspro. 重要提示: CSS font-family将转换为小写+ nospace,因此“Source Sans Pro”将成为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 Composer安装后脚本

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. 使用作曲家安装后脚本的方便的解决方法可以为您完成,而不是复制所有字体并将其添加到git。

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 ,其中包含以下内容:

*
!.gitignore
!SourceSansPro-Regular.ttf
!SourceSansPro-Bold.ttf

This will ignore everything except the .gitignore file and the fonts you wish to add. 这将忽略除.gitignore文件和您要添加的字体之外的所有内容。

Next, add the following scripts to your composer.json file: 接下来,将以下脚本添加到composer.json文件中:

"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. 经测试可与6.1一起使用。
In 7.x, the author implemented an elegant way to add external fonts. 在7.x中,作者实现了一种优雅的方式来添加外部字体。

Following are the steps to add new font family in mpdf library: 以下是在mpdf库中添加新字体系列的步骤:

  1. Download the font zip and unzip it. 下载字体zip并解压缩。
  2. Add new newFont.ttf font file(s) to this location /mpdf/ttfonts folder. 将新的newFont.ttf字体文件添加到此位置/mpdf/ttfonts文件夹。
  3. Edit /mpdf/config_fonts.php OR /mpdf/src/config/FontVariables.php to add an entry to the $this->fontdata array for the new font file(s). 编辑/mpdf/config_fonts.php/mpdf/src/config/FontVariables.php为新字体文件的$this->fontdata数组添加一个条目。 Like: 喜欢:

     $this->fontdata = array( "newFont" => array( 'R' => "newFont-Regular.ttf", 'B' => "newFont-Bold.ttf", 'I' => "newFont-Italic.ttf", 'BI' => "newFont-BoldItalic.ttf", ), 
  4. font-family: 'newFont'; is now available in the stylesheets. 现在可以在样式表中找到。

  5. $mpdfObj = new mPDF('', '', 'newFont'); $mpdfObj->SetFont('newFont');

  6. Now your new font is added. 现在添加了新字体。

There is another "dirty" way to add fonts dynamically in the run-time aside to the lib files. 除了lib文件之外,还有一种在运行时动态添加字体的“脏”方法。 This was my solution because I wasn't able to modify config_fonts.pdf file since it was in vendor/ files and would be overwritten on library update. 这是我的解决方案,因为我无法修改config_fonts.pdf文件,因为它在供应商/文件中,并且会在库更新时被覆盖。

function add_custom_fonts_to_mpdf($mpdf, $fonts_list) {
    // Logic from line 1146 mpdf.pdf - $this->available_unifonts = array()...       
    foreach ($fonts_list as $f => $fs) {
        // add to fontdata array
        $mpdf->fontdata[$f] = $fs;

        // add to available fonts array
        if (isset($fs['R']) && $fs['R']) { $mpdf->available_unifonts[] = $f; }
        if (isset($fs['B']) && $fs['B']) { $mpdf->available_unifonts[] = $f.'B'; }
        if (isset($fs['I']) && $fs['I']) { $mpdf->available_unifonts[] = $f.'I'; }
        if (isset($fs['BI']) && $fs['BI']) { $mpdf->available_unifonts[] = $f.'BI'; }
    }
    $mpdf->default_available_fonts = $mpdf->available_unifonts;
}

Make sure to provide font paths relative to to mpdf's ttfonts/ dir 确保提供相对于mpdf的ttfonts/ dir的字体路径

IMPORTANT: CSS font-family will be transformed to lowercase + nospaces so "Source Sans Pro-Regular" will become sourcesanspro-regular 重要提示: CSS font-family将转换为小写+ nospace,因此“Source Sans Pro-Regular”将成为sourcesanspro-regular

For example here I'm adding 2 fonts and 3 font files because other font has regular and bold version: 例如,我在这里添加2个字体和3个字体文件,因为其他字体有常规和粗体版本:

$mpdf = new mPDF('utf-8', 'A4', '', '', 20, 15, 50, 25, 10, 10);
$custom_fontdata = array(
    'sourcesanspro-regular' => array(
        'R' => "../../../../wms/hr_frontend/job/internet/fonts/SourceSansPro-Regular/SourceSansPro-Regular.ttf" 
        // use 'R' to support CSS font-weight: normal
        // use 'B', 'I', 'BI' and etc. to support CSS font-weight: bold, font-style: italic, and both...
    ),
    'someotherfont' => array(
        'R' => "../../../../wms/hr_frontend/job/internet/fonts/someotherfont.ttf", // In CSS font-weight: normal
        'B' => "../../../../wms/hr_frontend/job/internet/fonts/someotherfont-bold.ttf" // In CSS font-weight: bold
    )
);
add_custom_font_to_mpdf($mpdf, $custom_fontdata);
$mpdf->WriteHTML($html);

This was for mpdf 5.x but hopefully it works for 6.x as well. 这是为mpdf 5.x,但希望它也适用于6.x. Did anyone try? 有人试过吗?

No need to show errors on the screen. 无需在屏幕上显示错误。 See all errors and warnings in log file like "error.log" of your php + apache(?) server. 查看日志文件中的所有错误和警告,如php + apache(?)服务器的“error.log”。 It help you to find and resolve the problem based on message in the log file. 它可以帮助您根据日志文件中的消息查找并解决问题。

I any case you should use recommend fonts - see mPDF manual. 我无论如何你应该使用推荐字体 - 请参阅mPDF手册。

Probably, you need to convert TrueType fonts into proper MPDF's format. 可能需要将TrueType字体转换为适当的MPDF格式。 ( http://mpdf1.com/manual/index.php?tid=409&searchstring=fonts ) http://mpdf1.com/manual/index.php?tid=409&searchstring=fonts

Mpdf add Arial font Mpdf添加Arial字体

  1. Download font file : https://github.com/JotJunior/PHP-Boleto-ZF2/blob/master/public/assets/fonts/arial.ttf 下载字体文件: https//github.com/JotJunior/PHP-Boleto-ZF2/blob/master/public/assets/fonts/arial.ttf

  2. Paste the arial.ttf to mpdf/ttfonts 将arial.ttf粘贴到mpdf / ttfonts

  3. Open config_fonts.php and the below code with fontdata array 用fontdata数组打开config_fonts.php和下面的代码

    "arial" => array( 'R' => "arial.ttf", ), “arial”=> array('R'=>“arial.ttf”,),

simply add font to FontVariable.php 只需将字体添加到FontVariable.php即可

                "pacifico" => [
                'R' => "Pacifico.ttf",
                'useOTL' => 0xFF,
                'useKashida' => 75,
            ],

make sure if the ttf file name is start with capital letter like Pacifico.ttf then name the font family with start of small letter as i do on top . 确保ttf文件名是否以像Pacifico.ttf这样的大写字母开头,然后用小写字母开头命名字体系列,就像我在顶部一样。 eg make this pacifico and now simply test this with create testing php file 例如,制作这个pacifico ,现在只需用create testing php文件测试它

require_once __DIR__ . '/autoload.php';
$defaultConfig = (new Mpdf\Config\ConfigVariables())->getDefaults();
$fontDirs = $defaultConfig['fontDir'];
$defaultFontConfig = (new Mpdf\Config\FontVariables())->getDefaults();
$fontData = $defaultFontConfig['fontdata'];
$mpdf = new \Mpdf\Mpdf([
'mode' => 'utf-8',
'format' => 'A4'.('orientation' == 'L' ? '-L' : ''),
'orientation' => 0,
'margin_left' => 3,
'margin_right' => 3,
'margin_top' => 3,
'margin_bottom' => 0,
'margin_header' => 0,
'margin_footer' => 0,
]);    
$texttt= '
    <html>
    <p style="font-family: dejavusanscondensed;"> Text in Frutiger </p>
    <p style="font-family: freeserif;"> Text in Frutiger </p>
    <p style="font-family: freemono;"> Text in Frutiger </p>
    <p style="font-family: freeserif;"> مرحبا بالعالم </p>
    <p style="font-family: unbatang;"> 하는 바에 의하여 영장제도 </p>
    <p style="font-family: centurygothic;"> Text in Frutiger </p>
    <p style="font-family: pacifico;"> Text in Frutiger </p>
    <p style="font-family: windsong;"> Text in Frutiger </p>
    </html>';
     $mpdf->WriteHTML($texttt,\Mpdf\HTMLParserMode::HTML_BODY);
$mpdf->Output();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM