mpdf

一、说明

公司新项目有一个将数据导出PDF文件格式的需求,所以花了半天的时间在网上到处找技术成熟的轮子,试了好几个,最后发现mPDF这个轮子最好用,做完了功能,写篇总结,希望带给有同样需求的朋友一些帮助。

二、安装

window环境需要在dos系统跳转到项目根目录,执行命令:

composer require niklasravnsborg/laravel-pdf

三、配置

  1. 打开文件:/config/app.php,添加如下两条配置信息:
'providers' => [
    ……
    niklasravnsborg\LaravelPdf\PdfServiceProvider::class
]
 
'aliases' => [
    ……
    'PDF' => niklasravnsborg\LaravelPdf\Facades\Pdf::class
]
  1. 在config下添加pdf.php配置文件,配置信息如下:
 'custom',
    // ConstructorParams
    'mode'              => 'zh-cn',    // 中文显示
    'format'            => 'A4',
    'default_font_size' => 0,
    'default_font'      => '',
    'margin_left'       => 15,
    'margin_right'      => 15,
    'margin_top'        => 16,
    'margin_bottom'     => 16,
    'margin_header'     => 9,
    'margin_footer'     => 9,
    'orientation'       => 'P',
    /**
     * Set custom temporary directory
     * The default temporary directory is vendor/mpdf/mpdf/tmp
     *
     * @see https://mpdf.github.io/installation-setup/folders-for-temporary-files.html
     * Comment the following line to keep the temporary directory
     */
    'tempDir' => storage_path('app/pdf/tmp'), // absolute path
    /**
     * Custom Fonts
     *  1) Add your custom fonts to one of the directories listed under
     * 'fontDir' in which Mpdf will look for fonts
     *
     * 2) Define the name of the font and its configuration under the array 'fontdata'
     *
     * @see https://mpdf.github.io/fonts-languages/fonts-in-mpdf-7-x.html
     */
    // List of Directories Containing fonts (use absolute path)
    'fontDir'           => [
        storage_path('app/pdf/fonts'), // absolute path
        // add extra directory here
    ],
    // Fonts Configurations
    'fontdata'          => [
        // font name should be lower-case and contain no spaces
        'customfontname' => [
            'R'          => 'RegularCustomFont.ttf',
            'B'          => 'BoldCustomFont.ttd',
            'useOTL'     => 255,
            'useKashida' => 75,
        ],
        // lower-case and contain no spaces
        'arabic-font' => [
            'R'          => 'Montserrat-Arabic-Regular.ttf',
            'B'          => 'Montserrat-Arabic-Bold.ttf',
            'useOTL'     => 255,
            'useKashida' => 75,
        ],
        'shabnam' => [
            'R'          => 'Shabnam.ttf',
            'useOTL'     => 255,
            'useKashida' => 75,
        ],
    ],
];

四、基本使用

  1. 直接在网页上渲染PDF文件
$pdf = \PDF::loadHTML('HTML内容');
return $pdf->stream();
  1. 直接下载生成的PDF文件
$pdf = \PDF::loadHTML('HTML内容');
return $pdf->download('document.pdf');
  1. 通过模版文件渲染PDF
// 准备动态数据
$data = ['abc', 'efg'];
// 调用模版文件渲染(模版文件位于/resource/view/pdf.php)
$pdf = \PDF::loadView('pdf', ['data'=>$data]);
// 直接在页面渲染显示PDF
return $pdf->stream('show.pdf');
// 直接下载生成的PDF文件

————————————————
版权声明:本文为CSDN博主「追风2019」的原创文章,遵循CC 4.0 by-sa版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/createNo_1/article/details/83341070

你可能感兴趣的:(mpdf)