当前位置: 移动技术网 > IT编程>开发语言>PHP > PHP中使用mpdf 导出PDF文件的实现方法

PHP中使用mpdf 导出PDF文件的实现方法

2018年11月03日  | 移动技术网IT编程  | 我要评论

mpdf是一个很强大的pdf生成库,能基本兼容html标签和css3样式,这篇文章通过实例代码给大家介绍php中使用mpdf 导出pdf文件的实现方法。

具体代码如下所示:

/**
 * 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);

总结

以上所述是小编给大家介绍的php中使用mpdf 导出pdf文件的实现方法,希望对大家有所帮助

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网