Search code examples
phploopsmpdfmultiple-processes

Want to generate multiple pdf in single file using mpdf


I am generating multiple files using mpdf lib, I don't want to generate all files separately, I want to generate files in one pdf separated by pages.

I added the addpage method to generate a single file but having an issue, my first-page printing as expected but the second page is blank. I know I need to unset the dom because this lib works with generating new instances for multiple files.

Then I decided to unset the dom in the loop, and when my loop iterations are completed it says $mpdf var doesn't exist. Is there any other way to unset the dom for generating multiple pages on a single file?

If I add the unset at the end of the file only the first-page works successfully but the second leaves blank.

 for ($i=1; $i<count($sheetData); $i++) {
  $mpdf = new \Mpdf\Mpdf(['mode' => 'utf-8', 'format' => [290, 236]]);
                      $stylesheet = file_get_contents('style.css');
                      
                      $mpdf->WriteHTML($stylesheet, \Mpdf\HTMLParserMode::HEADER_CSS);
                     $html = $mpdf->WriteHTML('Hello World');
                     $filename = $key.''.time().'.pdf';
                      $targetPath = 'challans/Multiple/'.$dirName.'/';
                     
                     $mpdf->AddPage();  
                      
                  }  
                  $mpdf->Output($targetPath.$filename, 'F');
                  unset($mpdf);


Solution

  • Create the new instance outside of the loop and it works like a charm, also remove the $mpdf->AddPage(); method because it's automatically assigning the new page.

    Like

    for ($i=1; $i<count($sheetData); $i++) {
      $mpdf = new \Mpdf\Mpdf(['mode' => 'utf-8', 'format' => [290, 236]]);
    }
    

    To

    $mpdf = new \Mpdf\Mpdf(['mode' => 'utf-8', 'format' => [290, 236]]);
    for ($i=1; $i<count($sheetData); $i++) {
    }
    
    $mpdf->Output($targetPath.$filename, 'F');
    unset($mpdf);