PHP项目Barryvdh DomPDF中文

wen PHP项目 2

本文目录导读:

PHP项目Barryvdh DomPDF中文

  1. 主要问题及解决方案
  2. 推荐配置

我来帮您解决在Barryvdh DomPDF中使用中文的问题。

主要问题及解决方案

中文乱码问题

DomPDF默认不支持中文,需要配置中文字体。

解决方案 - 使用中文字体

使用系统字体(推荐)

// 在 config/dompdf.php 中配置
'font_dir' => storage_path('fonts'), // 自定义字体目录
'font_cache' => storage_path('fonts'),
'default_font' => 'simsun', // 设为中文字体

自定义字体配置

config/dompdf.php 中添加:

'font_families' => [
    'simsun' => [
        'normal' => storage_path('fonts/simsun.ttf'),
        'bold' => storage_path('fonts/simsun.ttf'),
        'italic' => storage_path('fonts/simsun.ttf'),
        'bold_italic' => storage_path('fonts/simsun.ttf'),
    ],
    'simhei' => [
        'normal' => storage_path('fonts/simhei.ttf'),
        // 其他样式...
    ],
],

HTML中使用中文

// 在视图中使用
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <style>
        body {
            font-family: 'simsun', 'simhei', sans-serif;
        }
    </style>
</head>
<body>
    <h1>中文标题</h1>
    <p>这是中文内容</p>
</body>
</html>

完整示例代码

use Barryvdh\DomPDF\Facade\Pdf;
class OrderController extends Controller
{
    public function generatePDF($id)
    {
        $order = Order::find($id);
        $pdf = Pdf::loadView('pdf.order', compact('order'));
        // 设置纸张大小和方向
        $pdf->setPaper('A4', 'portrait');
        // 设置选项
        $pdf->setOptions([
            'defaultFont' => 'simsun',
            'isHtml5ParserEnabled' => true,
            'isRemoteEnabled' => true,
        ]);
        return $pdf->download('order-'.$id.'.pdf');
    }
}

安装中文字体

# 1. 创建字体目录
mkdir -p storage/fonts
# 2. 下载中文字体文件(如 simsun.ttf)
# 将字体文件放入 storage/fonts/ 目录
# 3. 重新生成字体缓存
php artisan dompdf:reset

替代方案 - 使用Google Fonts(需要网络)

// 在视图中引入
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@400;700&display=swap" rel="stylesheet">
<style>
    body {
        font-family: 'Noto Sans SC', sans-serif;
    }
</style>

调试技巧

// 查看PDF生成错误
try {
    $pdf = Pdf::loadView('pdf.test');
    return $pdf->download('test.pdf');
} catch (\Exception $e) {
    dd($e->getMessage());
}
// 直接在浏览器显示PDF
return $pdf->stream('document.pdf');

常见问题解决

问题1:字体文件过大

  • 使用subset字体文件
  • 只包含需要的字符集

问题2:性能问题

// 缓存PDF
$pdf = Pdf::loadView('pdf.invoice');
$pdf->save(storage_path('app/invoices/invoice-'.$id.'.pdf'));

问题3:特殊字符显示

// 使用HTML实体
echo htmlspecialchars('中文内容', ENT_QUOTES, 'UTF-8');

推荐配置

创建字体配置文件 config/dompdf.php

return [
    'show_warnings' => false,
    'orientation' => 'portrait',
    'defines' => [
        'font_dir' => storage_path('fonts/'),
        'font_cache' => storage_path('fonts/'),
        'temp_dir' => sys_get_temp_dir(),
        'chroot' => realpath(base_path()),
        'enable_font_subsetting' => true,
        'enable_remote' => false,
        'default_font' => 'simsun',
        'pdf_backend' => 'CPDF',
        'dpi' => 96,
        'enable_html5_parser' => true,
    ],
];

这样配置后,您的DomPDF就能正常显示中文了!

抱歉,评论功能暂时关闭!