骑缝章 使用mpdf生成,这里我有个坑迈不过去。

mpdf 版本 8.0+

就是使用 $mpdf->writeHtml($html); 生成pdf的过程中不能加盖骑缝章,因为不知道在那个地方插入图片这个命令,也没有分页的命令,找不到定位到pdf在哪一页的方法。所以找了一个比较傻缺的办法:首先生成pdf,然后把生成的pdf再生成一遍加入骑缝章。如果有更高的方法请告诉有代码洁癖的我 十分感谢。

下面是一个迂回的方法:

环境:thinkphp6  Mpdf8.1.2

第一步简单,就是自己生成一个pdf文件

$mpdf = new Mpdf([
    'autoScriptToLang' => true,
    'autoLangToFont' => true,
    'setAutoTopMargin' => 'stretch',
    'autoMarginPadding' => 3,
    'format' => 'A4',
    'orientation' => 'P',
    'adjustFontDescLineheight' => 1.4
]);

$head = $this->fetch("inc/report_head");
$mpdf->SetHTMLHeader($head);  //页眉

$reportInfo = $this->fetch("inc/report_info");
$itemInfo = $this->fetch("inc/report_item_list"); //两部分的主体
$styleSheet = <<<CSS
td{padding:10px;}
CSS;

$mpdf->WriteHTML($styleSheet,\Mpdf\HTMLParserMode::HEADER_CSS); //加载样式

//生成PDF
$mpdf->WriteHTML($reportInfo.'<pagebreak>'  . $itemInfo); 
$file_name = $report['report_num']."_".time() . '.pdf';
$mpdf->Output($file_name);

这样就得到了一个pdf文件 $file_name

然后第二步:

$mpdf2 = new Mpdf();
$pagecount = $mpdf2->setSourceFile($file_name);
for($i=1;$i<=$pagecount;$i++){
    $tplId = $mpdf2->importPage($i);
    $mpdf2->useTemplate($tplId);
    $imgPath = $this->cutImg("upload/zhang/zhang.png",$pagecount,$i);
    $mpdf2->Image($imgPath, (210-(40/$pagecount)), 70, 40/$pagecount, 40, 'png', '', true, false);
    if($i < $pagecount){
        $mpdf2->AddPage();
    }
}
$mpdf2->Output($file_name,true);
unlink($file_name);

获取 这个pdf文件的页数 然后每页插入一张图片;使用 cutImg() 这个方法;

public function cutImg($img_path,$cut_numbers,$use_index){
   $image = Image::open($img_path);
   $dirname = dirname($img_path);
   $basename = basename($img_path,'.'.$image->type());
   $out_path = $dirname."/".$basename."-".$cut_numbers.'-'.$use_index.".".$image->type();
   if(file_exists($out_path)){
      return $out_path;
   }
   $width = $image->width();
   $height = $image->height();
   $per_width = $width / $cut_numbers;
   $start = $per_width * ($use_index - 1);
   $image->crop($per_width,$height,$start,0);
   $image->save($out_path,$image->type());
   return $out_path;
}