Search code examples
phpfpdf

How to generate more than one PDF and send through email attachment using PHP?


How to generate more than one pdf and send with email attachment?

i am use fpdf php library to generate pdf and want to send multiple pdf attachment with email. so i have tried like,

<?php
require('fpdf.php');

// Generate first One.
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output('.assets/temp/download1.pdf','f');
$file1='.assets/temp/download1.pdf';

 // Generate Second PDF.
 $pdf = new FPDF();
 $pdf->AddPage();
 $pdf->SetFont('Arial','B',16);
 $pdf->Cell(40,10,'Hello World!');
 $pdf->Output('.assets/temp/download2.pdf','f');
 $file2='.assets/temp/download2.pdf';

 // use phpmailer to send email.
 // load attachments and messages.
 // send
 // unset files.
?>

this will create a error Message: FPDF error: The document is closed. because i cannot load two time without close document. so please ask me solution for send multiple pdfs through attachment.


Solution

  • Try using 'S' parameter istead of 'F'

    $pdf1 = new FPDF();
    $pdf1->AddPage();
    $pdf1->SetFont('Arial', 'B', 16);
    $pdf1->Cell(40, 10, 'Hello World1!');
    $file1 = ".assets/temp/download1.pdf";
    $pdf1content = $pdf1->Output('S');
    file_put_contents($file1, $pdf1content);
    
    $pdf2 = new FPDF();
    $pdf2->AddPage();
    $pdf2->SetFont('Arial', 'B', 16);
    $pdf2->Cell(40, 10, 'Hello World2!');
    /**/
    $file2 = ".assets/temp/download2.pdf";
    $pdf2content = $pdf2->Output('S');
    file_put_contents($file2, $pdf2content);
    
    // use phpmailer to send email.
    // load attachments and messages.
    // send unset files.
    

    see http://www.fpdf.org/en/doc/output.htm