mPDF是一个很强大的PDF生成库,能基本兼容HTML标签和CSS3样式,这篇文章通过实例代码给大家介绍PHP中使用mpdf 导出PDF文件的实现方法。
具体代码如下所示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
/**
* PHP 使用 mpdf 导出PDF文件
* @param $content string PDF文件内容 若为html代码,css内容分离 非id,class选择器可能失效,解决办法直接写进标签style中
* @param $filename string 保存文件名
* @param $css string css样式内容
*/
function
export_pdf_by_mpdf(
$content
,
$filename
,
$css
=
''
)
{
set_time_limit(0);
include_once
'./mpdf/mpdf.php'
;
//实例化mpdf
$_obj_mpdf
=
new
\mPDF(
'utf-8'
,
'A4'
,
''
,
'宋体'
, 0, 0, 20, 10);
//设置PDF页眉内容 (自定义编辑样式)
$header
= '<table width=
"95%"
style=
"margin:0 auto;border-bottom: 1px solid #4F81BD; vertical-align: middle; font-family:serif; font-size: 9pt; color: #000088;"
>
<tr><td width=
"10%"
></td><td width=
"80%"
align=
"center"
style=
"font-size:16px;color:#A0A0A0"
>页眉</td><td width=
"10%"
style=
"text-align: right;"
></td></tr></table>';
//设置PDF页脚内容 (自定义编辑样式)
$footer
= '<table width=
"100%"
style=
" vertical-align: bottom; font-family:serif; font-size: 9pt; color: #000088;"
><tr style=
"height:30px"
></tr><tr>
<td width=
"10%"
></td><td width=
"80%"
align=
"center"
style=
"font-size:14px;color:#A0A0A0"
>页脚</td><td width=
"10%"
style=
"text-align: left;"
>
页码:{PAGENO}/{nb}</td></tr></table>';
//添加页眉和页脚到PDF中
$_obj_mpdf
->SetHTMLHeader(
$header
);
$_obj_mpdf
->SetHTMLFooter(
$footer
);
$_obj_mpdf
->SetDisplayMode(
'fullpage'
);
//设置PDF显示方式
$_obj_mpdf
->WriteHTML(
'<pagebreak sheet-size="210mm 297mm" />'
);
//设置PDF的尺寸 A4纸规格尺寸:210mm*297mm
!
empty
(
$css
) &&
$_obj_mpdf
->WriteHTML(
$css
, 1);
//设置PDF css样式
$_obj_mpdf
->WriteHTML(
$content
);
//将$content内容写入PDF
$_obj_mpdf
->DeletePages(1, 1);
//删除PDF第一页(由于设置PDF尺寸导致多出的一页)
//输出PDF 直接下载PDF文件
//$_obj_mpdf->Output($filename . '.pdf', true);
//$_obj_mpdf->Output($filename . '.pdf', 'D');
$_obj_mpdf
->Output();
//输出PDF 浏览器预览文件 可右键保存
exit
;
}
$html
=
'<b style="color: red">你看我哪里像好人</b>'
;
$wordname
=
'test-file'
;
export_pdf_by_mpdf(
$html
,
$wordname
);
|