首先标明一下运行环境 tp5框架,PHP5.6+mpdf6.1.3,另外问题和获取到的html字符串有关系,普通字符串运行正常!!!
本来笔者是使用的PHP7.1的环境,运行mpdf8.0.5版本无压力,后来服务器环境所限,只能换成6.1版本,在此记录一下使用方法。
1、获取HTML页面,也可以使用纯手写方式。。。
$url = '****';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// 已经获取到内容,没有输出到页面上。
$html = curl_exec($ch);
curl_close($ch);
2、调用mpdf生成文件
//设置中文编码
$mpdf= new \mPDF('zh-CN','A4','', 'dejavusans', 20,20,20,20);
//设置中文字体
$mpdf->autoScriptToLang = true;
$mpdf->autoLangToFont = true;
$mpdf->useAdobeCJK = TRUE;
$mpdf->SetDisplayMode('fullpage');
$mpdf->SetHTMLHeader('');
$mpdf->SetHTMLFooter('');
$mpdf->WriteHTML($html);
//D是在浏览器生成pdf文件另存为 I是直接显示生成的pdf文件
$mpdf->Output($file_path,'F');
运行时报错division by zero,询问度娘找到少量资料,在坑里蹲了一天,想起来去github去看看问题,发现是旧版本代码问题,新版已修复,所以找到了最新版代码加到了旧版中
$target = $h / $w;
在mpdf.php类中找到这句话,然后后面运行代码加上非零判断即可。
if ($overflow != 'hidden' && $overflow != 'visible') {
$target = $h / $w;
if ($target > 0) {
if (($ratio / $target) > 1) {
$nl = CEIL($actual_h / $this->lineheight);
$l = $use_w * $nl;
$est_w = sqrt(($l * $this->lineheight) / $target) * 0.8;
$use_w += ($est_w - $use_w) - ($w / 100);
}
$bpcstart = ($ratio / $target);
$bpcctr = 1;
while (($ratio / $target) > 1) {
if ($this->progressBar) {
$this->UpdateProgressBar(4, intval(100 / ($ratio / $target)), ('Auto-sizing fixed-position block: ' . $bpcctr++));
} // *PROGRESS-BAR*
$this->x = $x;
$this->y = $y;
if (($ratio / $target) > 1.5 || ($ratio / $target) < 0.6) {
$use_w += ($w / $this->incrementFPR1);
} elseif (($ratio / $target) > 1.2 || ($ratio / $target) < 0.85) {
$use_w += ($w / $this->incrementFPR2);
} elseif (($ratio / $target) > 1.1 || ($ratio / $target) < 0.91) {
$use_w += ($w / $this->incrementFPR3);
} else {
$use_w += ($w / $this->incrementFPR4);
}
$use_h = $use_w * $target;
$this->rMargin = $this->w - $use_w - $x;
$this->pgwidth = $this->w - $this->lMargin - $this->rMargin;
$this->HTMLheaderPageLinks = array();
$this->HTMLheaderPageAnnots = array();
$this->HTMLheaderPageForms = array();
$this->pageBackgrounds = array();
$this->WriteHTML($html, 4); // parameter 4 saves output to $this->headerbuffer
$actual_h = $this->y - $y;
$ratio = $actual_h / $use_w;
}
}
if ($this->progressBar) {
$this->UpdateProgressBar(4, '100', ' ');
} // *PROGRESS-BAR*
}
笔者是compose安装的,代码可能和手动下载的mpdf版本略有区别