laravel 10 HTML转PDF

1. 安装 mpdf/mpdf

通过 Composer 在您的 Laravel 项目根目录下安装该包:

composer require mpdf/mpdf

2. 基本使用

示例:在控制器中生成一个简单的 PDF 并下载

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Mpdf\Mpdf;

class PdfController extends Controller
{
    public function generatePdf()
    {
        // 1. 初始化 mPDF
        $mpdf = new Mpdf();

        // 2. 设置 PDF 内容 (可以是 HTML 字符串)
        $html = '<h1>Hello World!</h1>';
        $html .= '<p>这是使用 mPDF 在 Laravel 中生成的第一份 PDF。</p>';
        
        // 3. 将 HTML 内容写入 PDF
        $mpdf->WriteHTML($html);

        // 4. 输出 PDF 到浏览器(强制下载)
        return $mpdf->Output('document.pdf', \Mpdf\Output\Destination::DOWNLOAD);

        // 其他输出选项:
        // return $mpdf->Output('document.pdf', \Mpdf\Output\Destination::INLINE); // 在浏览器中内嵌查看
        // return $mpdf->Output('document.pdf', \Mpdf\Output\Destination::FILE); // 保存到服务器上的某个路径
    }
}

3. 使用Blade模板

步骤 1:创建 Blade 模板文件
在 resources/views/pdf 目录下创建 report.blade.php

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>{{ $title }}</title>
    <style>
        body { font-family: DejaVu Sans, sans-serif; }
        /* 必须使用支持中文的字体,否则中文会显示为乱码 */
        .header { text-align: center; margin-bottom: 20px; }
        table { width: 100%; border-collapse: collapse; }
        table, th, td { border: 1px solid black; }
        th, td { padding: 8px; text-align: left; }
    </style>
</head>
<body>
    <div class="header">
        <h1>{{ $title }}</h1>
        <p>生成于: {{ $date }}</p>
    </div>

    <table>
        <thead>
            <tr>
                <th>ID</th>
                <th>名称</th>
                <th>邮箱</th>
            </tr>
        </thead>
        <tbody>
            @foreach($users as $user)
                <tr>
                    <td>{{ $user->id }}</td>
                    <td>{{ $user->name }}</td>
                    <td>{{ $user->email }}</td>
                </tr>
            @endforeach
        </tbody>
    </table>
</body>
</html>

步骤 2:在控制器中使用模板并传递数据

public function generateReport()
{
    // 模拟数据(通常是从数据库获取)
    $users = User::limit(10)->get(); 
    $date = now()->format('Y-m-d H:i:s');
    $title = "用户报告";

    // 将 Blade 视图渲染为 HTML 字符串
    $html = view('pdf.report', compact('users', 'date', 'title'))->render();

    // 配置 mPDF(解决中文乱码等常见问题)
    $mpdf = new Mpdf([
        'mode' => 'utf-8',
        'format' => 'A4',
        'default_font' => 'simsun', // 使用宋体,支持中文
        'margin_left' => 15,
        'margin_right' => 15,
        'margin_top' => 16,
        'margin_bottom' => 16,
    ]);

    $mpdf->WriteHTML($html);
    
    // 在浏览器中内嵌显示
    return $mpdf->Output('用户报告.pdf', \Mpdf\Output\Destination::INLINE);
}
处理中文乱码问题

中文乱码是使用 mpdf 时最常见的问题,需要通过以下两步解决:

1.在构造函数中正确配置

$mpdf = new Mpdf([
    'mode' => 'utf-8',
    'format' => 'A4',
    'default_font' => 'simsun', // 关键:指定一个支持中文的字体
]);

mpdf 内置了一些支持中文的字体,如 simsun(宋体)、simhei(黑体)、dejavusans(支持多语言,但可能不美观)。

2.在 Blade 模板的 CSS 中指定字体

body {
    font-family: DejaVu Sans, simsun, sans-serif;
}

3.引入中文字体

$mpdf = new Mpdf([
            'mode' => 'utf-8',
            'format' => 'A4',
            'default_font' => 'simsun', // 关键:指定一个支持中文的字体
            //直接window字体里找到,放到项目目录里直接引用
            'fontDir' => [
                storage_path('fonts'), // 自定义字体目录
            ],
            'fontdata' => [
                'simsun' => [
                    'R' => 'simsun.ttf',
                    'TTCfontID' => [ // 关键:指定字体索引
                        'R' => 0, // 通常宋体的索引是 0
                    ],
                    'useOTL' => 0xFF,
                ],
            ],
        ]);

亲测配置

        // 配置临时文件目录
        $tempDir = storage_path('app/public/mpdf/tmp');


        // 默认配置
        $defaultConfig = [
            'tempDir' => $tempDir, //设置临时目录
            'mode' => 'utf-8',
            'format' => 'A4',
            'default_font' => 'simsun',
            'margin_left' => 10,
            'margin_right' => 10,
            'margin_top' => 10,
            'margin_bottom' => 10,
            'fontDir' => [
                storage_path('fonts'), // 自定义字体目录,字体直接windows字体库复制到项目目录下
            ],
            'fontdata' => [
                'simsun' => [
                    'R' => 'simsun.ttf',
                    'TTCfontID' => [ // 关键:指定字体索引
                        'R' => 0, // 通常宋体的索引是 0
                    ],
                    'useOTL' => 0xFF,
                ],
            ],
        ];

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值