liuhongdi@lhdpc:/data/php/admapi$ composer show mpdf/mpdf
name : mpdf/mpdf
descrip. : PHP library generating PDF files from UTF-8 encoded HTML
keywords : pdf, php, utf-8
versions : * v8.0.15
type : library
license : GNU General Public License v2.0 only (GPL-2.0-only) (OSI approved) https://spdx.org/licenses/GPL-2.0-only.html#licenseText
homepage : https://mpdf.github.io
source : [git] https://github.com/mpdf/mpdf.git d8a5294a6cc2e814c4157aecc8d7ac25014b18ed
dist : [zip] https://api.github.com/repos/mpdf/mpdf/zipball/d8a5294a6cc2e814c4157aecc8d7ac25014b18ed d8a5294a6cc2e814c4157aecc8d7ac25014b18ed
path : /data/php/admapi/vendor/mpdf/mpdf
names : mpdf/mpdf
可以看到版本是 v8.0.15
说明:刘宏缔的架构森林是一个专注架构的博客,
网站:https://blog.imgtouch.com
本文: https://blog.imgtouch.com/index.php/2023/05/29/thinkphp6-yong-mpdf-sheng-cheng-pdf-wen-jian-php-8-1-1/
对应的源码可以访问这里获取: https://github.com/liuhongdi/
或: https://gitee.com/liuhongdi
说明:作者:刘宏缔 邮箱: 371125307@qq.com
二,编写php代码
controller/Index.php
<?php
namespace app\controller;
use app\BaseController;
use app\result\Result;
use Mpdf\Mpdf;
class Index extends BaseController
//创建pdf文件
public function makePdf() {
$id=123;
//用html形式生成pdf
$html_content = '<p style="text-align: center;">
<span style="color: rgb(153, 0, 0); font-size: 15px; text-align: center;">
<img src="https://imgs-qn.iliangcang.com/ware/slider/1775.jpg" title="191335ODA5NzgyNzMwMzAy.jpg" alt="QQ截图20200306180410.jpg"/>
</span>
<p style="text-align: center;">
<span style="color: rgb(153, 0, 0); font-size: 15px; text-align: center;">
一年一度春节伴手礼大赛,带什么全家最开心?
</span>
<p style="text-align: center;">
<img src="http://img.baidu.com/hi/jx2/j_0034.gif"/>
<img src="http://img.baidu.com/hi/jx2/j_0040.gif"/>
</p>';
//tempDir指定临时文件目录,需要有可写入的权限,否则会报错
$mpdf = new Mpdf(['mode'=>'utf-8',
'format' => 'A4',
'tempDir' => '/var/www/html/tmp'
$mpdf->SetDisplayMode('fullpage');
//自动分析录入内容字体
$mpdf->autoScriptToLang = true;
$mpdf->autoLangToFont = true;
//文章pdf文件存储路径
$fileUrl = "/var/www/html/pdf/article_".$id.".pdf";
//以html为标准分析写入内容
$mpdf->WriteHTML($html_content);
//生成文件
$mpdf->Output($fileUrl);
//判断是否生成文件成功
if (is_file($fileUrl)){
return Result::Success("文件生成成功");
} else {
return Result::Error(1,"文件生成失败");
//下载pdf文件
public function downPdf() {
$id=123;
$fileUrl = "/var/www/html/pdf/article_".$id.".pdf";
return download($fileUrl,"article_".$id.".pdf");
三,测试效果
1,生成pdf:
查看内容:
2,下载pdf
http://192.168.219.6:8000/index/downpdf
访问后文件会下载到本地
四,查看php和thinkphp的版本:
liuhongdi@lhdpc:/data/php/admapi$ php --version
PHP 8.1.1 (cli) (built: Dec 20 2021 16:12:16) (NTS)
thinkphp:
liuhongdi@lhdpc:/var/www/html$ cd /data/php/admapi/
liuhongdi@lhdpc:/data/php/admapi$ php think version
v6.0.10LTS