首页 > 解决方案 > mPDF 合并多个文件 pdf

问题描述

我正在使用最新版本的 MPDF。此代码有效。我合并了几个文件。我没有得到回报。如果您注释掉 foreach,则返回。也许我没有正确团结?

 list($directorySite, $shell) = explode('app', __DIR__);
    require($directorySite.'/vendor/autoload.php');
    try {
        $mpdf = new Mpdf(['mode' => 'utf-8']);
        $mpdf->SetImportUse();
        $page1 = $mpdf->SetSourceFile('public/scanInvoice/'.$resultJPGtoPDF);
        for ($i=1;$i<=$page1;$i++) {
            $mpdf->AddPage();
            $tplId = $mpdf->ImportPage($i);
            $mpdf->UseTemplate($tplId);
            $mpdf->WriteHTML('');
        }
        foreach ($pathsPDF as $item){
            $page2 = $mpdf->SetSourceFile('public/scanInvoice/'.$item);
            for ($i=1;$i<=$page2;$i++) {
                $mpdf->AddPage();
                $tplId = $mpdf->ImportPage($i);
                $mpdf->UseTemplate($tplId);
                $mpdf->WriteHTML('');
            }
        }
        $preName = $this->translit('JPEGandPDF');
        $mpdf->Output($direct.DIRECTORY_SEPARATOR.$preName.'.pdf', 'F');
        return $preName.'.pdf';
    } catch (MpdfException $e) {
        return $e->getMessage();
    }

标签: phpmpdf

解决方案


我知道帖子很旧,但这可能会对某人有所帮助。我正在使用 PHP 7.3 和 mpdf 8 对 PDF 进行分组,将分组文件保存到磁盘,这对我来说很好:

$files = array();//the files to merge
$files[] = DIR_UPLOAD. 'gls/batch_11/labels_45812.pdf';
$files[] = DIR_UPLOAD. 'gls/batch_11/labels_45818.pdf';
$files[] = DIR_UPLOAD. 'gls/batch_11/labels_45820.pdf';

$output= DIR_UPLOAD. 'gls/batch_11/labels.pdf';//where to save the combined file


require_once(DIR_SYSTEM.'library/mpdf/vendor/autoload.php');
$mpdf=new \Mpdf\Mpdf(['tempDir' => DIR_SYSTEM.'library/mpdf/tmp', 'format'=> 'a6', 'orientation'=> 'L']);//A6 format landscape

    $file_counter=1;//to be used in the loop
    foreach($files AS $file)
    {
          $pagecount = $mpdf->SetSourceFile($file);
          for($i=0; $i< $pagecount; $i++)
          {
              $tplId = $mpdf->importPage($i+1);
              $mpdf->useTemplate($tplId);

                  //add a page except for the last loop of the last document (otherwise we have a blank page)
                  if( $file_counter != count($files) ||   ($i+1) != $pagecount)
                  {
                    $mpdf ->addPage();
                  }

          }//end for
      $file_counter++;
    }//end foreach

    $mpdf->Output($output);//save the file

推荐阅读