php 将字体添加到 mPDF

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17586409/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:08:51  来源:igfitidea点击:

adding font to mPDF

phpfontsmpdf

提问by Paul Dessert

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 ttfontsdirectory and defined the font in config_fonts.phplike 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?

知道我做错了什么吗?

回答by Ajai

Following are the steps to add new font family in mpdf library:

以下是在 mpdf 库中添加新字体系列的步骤:

  1. Download the font zip and unzip it.
  2. Add new newFont.ttffont file(s) to this location /mpdf/ttfontsfolder.
  3. Edit /mpdf/config_fonts.phpOR /mpdf/src/config/FontVariables.phpto add an entry to the $this->fontdataarray for the new font file(s). 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.

  1. 下载字体 zip 并解压。
  2. 将新newFont.ttf字体文件添加到此位置/mpdf/ttfonts文件夹。
  3. 编辑/mpdf/config_fonts.phpOR/mpdf/src/config/FontVariables.php以将条目添加到$this->fontdata新字体文件的数组中。喜欢:

    $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';现在在样式表中可用。

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

  6. 现在您的新字体已添加。

回答by s3v3n

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.

基于@hrvoje-golcic 的答案,这里有一种改进的、不那么脏的方法,无需编辑即可将字体添加到 mPDF 中config_fonts.php。我正在使用 Laravel,我使用 Composer 安装了 mPDF。

  1. As suggested by the author, define a constant named _MPDF_TTFONTPATHbefore initializing mPDFwith the value as the path to your ttfontsfolder (this constant exists since at least 5.3).
  2. Copy the vendor/mpdf/mpdf/ttfontsfolder to a location that you control (outside of the vendor folder).
  3. Add your custom fonts to that folder along with the others.
  4. Add your configuration to the fontdataproperty on the mPDFinstance.
  1. 正如作者所建议的,_MPDF_TTFONTPATH在初始化之前定义一个常量,mPDF使用该值作为ttfonts文件夹的路径(该常量至少从 5.3 开始就存在)。
  2. vendor/mpdf/mpdf/ttfonts文件夹复制到您控制的位置(在供应商文件夹之外)。
  3. 将您的自定义字体与其他字体一起添加到该文件夹​​中。
  4. 将您的配置添加到实例的fontdata属性中mPDF

Heads up: The ttfontsfolder 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 transformedto lowercase + nospaces so "Source Sans Pro" will become sourcesanspro.

注意:该ttfonts文件夹大约有 90MB,所以可能还有更好的方法,但是您必须复制所有字体,因为原始配置添加了它们。请参阅此答案底部的作曲家脚本替代方案。

重要提示:CSS font-family 将被转换为小写 + nospaces,因此“Source Sans Pro”将成为 sourceanspro。

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,使用 Composer 安装后脚本的便捷解决方法可以为您做到这一点。

First of all, make sure the folder where you wish to copy the fonts exists, and create a .gitignorein it, with the following contents:

首先,确保要复制字体的文件夹存在,并.gitignore在其中创建一个,内容如下:

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

This will ignore everything except the .gitignorefile and the fonts you wish to add.

这将忽略除.gitignore文件和您要添加的字体之外的所有内容。

Next, add the following scripts to your composer.jsonfile:

接下来,将以下脚本添加到您的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.
In 7.x, the author implementedan elegant way to add external fonts.

这经过测试可以与 6.1 一起使用。
在 7.x 中,作者实现了一种优雅的方式来添加外部字体。

回答by Hrvoje Golcic

There is another "dirty" way to add fonts dynamically in the run-time aside to the lib files. This was my solution because I wasn't able to modify config_fonts.pdffile since it was in vendor/ files and would be overwritten on library update.

还有另一种“肮脏”的方式可以在运行时动态地将字体添加到 lib 文件中。这是我的解决方案,因为我无法修改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

IMPORTANT:CSS font-family will be transformed to lowercase + nospaces so "Source Sans Pro-Regular" will become sourcesanspro-regular

确保提供相对于 mpdfttfonts/目录的字体路径

重要提示:CSS font-family 将转换为小写 + nospaces,因此“Source Sans Pro-Regular”将变为 sourceanspro-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. Did anyone try?

这适用于 mpdf 5.x,但希望它也适用于 6.x。有人试过吗?

回答by Er Mandeep

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.ttfthen name the font family with start of small letter as i do on top . e.g make this pacificoand now simply test this with create testing php file

确保 ttf 文件名是否以大写字母开头,如Pacifico.ttf,然后像我在顶部那样以小写字母开头命名字体系列。例如制作这个pacifico,现在只需使用创建测试 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();

回答by Mohd Bashir

Mpdf add Arial font

Mpdf 添加 Arial 字体

  1. Download font file : https://github.com/JotJunior/PHP-Boleto-ZF2/blob/master/public/assets/fonts/arial.ttf

  2. Paste the arial.ttf to mpdf/ttfonts

  3. Open config_fonts.php and the below code with fontdata array

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

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

  2. 将 arial.ttf 粘贴到 mpdf/ttfonts

  3. 用 fontdata 数组打开 config_fonts.php 和下面的代码

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

回答by Intacto

No need to show errors on the screen. See all errors and warnings in log file like "error.log" of your php + apache(?) server. It help you to find and resolve the problem based on message in the log file.

无需在屏幕上显示错误。查看日志文件中的所有错误和警告,例如 php + apache(?) 服务器的“error.log”。它可以帮助您根据日志文件中的消息查找并解决问题。

I any case you should use recommend fonts - see mPDF manual.

在任何情况下,您都应该使用推荐字体 - 请参阅 mPDF 手册。

Probably, you need to convert TrueType fonts into proper MPDF's format. (http://mpdf1.com/manual/index.php?tid=409&searchstring=fonts)

可能,您需要将 TrueType 字体转换为正确的 MPDF 格式。( http://mpdf1.com/manual/index.php?tid=409&searchstring=fonts)