0
点赞
收藏
分享

微信扫一扫

laravel 使用mpdf将html转化成pdf

墨春 2023-09-16 阅读 51
  • 安装方式
    composer require mpdf/mpdf

  • 常用配置

$defaultConfig = (new \Mpdf\Config\ConfigVariables())->getDefaults();
// 获取默认的字体包文件路径
$fontDirs = $defaultConfig['fontDir'];

$defaultFontConfig = (new \Mpdf\Config\FontVariables())->getDefaults();
// 获取默认的字体包
$fontData = $defaultFontConfig['fontdata'];
$options = [ 
    'debug'=>true,
    'mode' => 'utf-8',
    'format' => 'A4',
    'useAdobeCJK' => true,
    'baseScript'=>1,
    'autoVietnamese'=>true,
    'autoArabic'=>true,
    'autoScriptToLang' => true,
    // 'autoLangToFont'   => true,
    'useSubstitutions' => true,
    'mgl' => 0,
    'mgr' => 0,
    'mgt' => 0,
    'mgb' => 0,
    'mgh' => 0,
    'mgf' => 0,
    'margin_left' => 10,
    'margin_right' => 10,
    'margin_top' => 10,
    'margin_bottom' => 16,
    'orientation' => 'P',
    // 'setAutoTopMargin' => 'stretch', 
    'setAutoBottomMargin' => 'stretch',
    'default_font_size' => 14,
	'fontDir' => array_merge($fontDirs, [
        public_path('ttf')
    ]),
    'fontdata' => $fontData + 
        [
            'customsongti' => [
                // 宋体
                'R' => 'songti.ttf'
            ],
            'customtimes'=>[
                // 新罗马斜体
                'R'=>'TimesNewRomanItalic.ttf'
            ]
        ],
    'default_font'=>'customsongti'
];
// 匹配所有的斜体中的字母和数字
 $html = preg_replace_callback('/<span style="(.*)">(.*)<\/span>/isU',function($matches){
 			// 如果有斜体样式
            if(strpos($matches[1],'font-style:italic;') !== false){
                $text = $matches[2];
                // 要用新字体的字符
                $chars = ['a',  'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z','A','B','C','D','E','F','G'.'H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','X','Y','Z','+','-','=','0','1','2','3','4','5','6','7','8','9'];
                // 匹配字符
                $preg = '/['.implode('',$chars).']+/isu';
                $text = preg_replace_callback($preg,function($matches){
                        $chars = $matches[0];
                        // 给指定的字符加样式类
                        return '<span class="mathChars">'.$chars.'</span>';
                },$text);
                // 原有的样式依旧保留
                return '<span style="'.$matches[1].'">'.$text.'</span>';
            }else{
                return $matches[0];
            }
        }, $html);
举报

相关推荐

0 条评论