0

I have a series of base64 PDF Files that I would like to merge together. Currently I am using file_get_contents() and with PHPMailer can attach each of them separately.

$woFile = file_get_contents($url);
$invoiceFile = file_get_contents($invPDF64);
$tsFile = file_get_contents($tsPDF64);
...
$mail->AddStringAttachment($woFile, "1.pdf", "base64", "application/pdf");
$mail->AddStringAttachment($invoiceFile, "2.pdf", "base64", "application/pdf");
$mail->AddStringAttachment($tsFile, "3.pdf", "base64", "application/pdf");

All the examples I've seen online such as FPDF require the file to be locally downloaded, at least from what I saw. Is there a way to append each of these PDF files into one, and then have that attached to the email?

Thanks in advance!

Tino
  • 539
  • 2
  • 6
  • 18

1 Answers1

1

I'm not sure if you specifically need to merge the PDFs into one PDF, or if you just want one file. Here are options for both:

  1. If you want to merge all PDFs into a single PDF file, then this is a duplicate question. You mention not wanting to have a local file, but this may be an unreasonable constraint (e.g., memory issues with large PDFs). Use temporary files as appropriate and clean up after yourself.
  2. If you just want a single file, consider putting the files into a ZIP archive and sending that. You might also like the ZipStream library for this purpose. Here's some minimal code using the native library:

    $attachmentArchiveFilename = tempnam('tmp', 'zip');
    $zip = new ZipArchve();
    
    # omitting error checking here; don't do it in production
    $zip->open($attachmentArchiveFilename, ZipArchve::OVERWRITE);
    $zip->addFromString('PDFs/first.pdf', $woFile);
    $zip->addFromString('PDFs/second.pdf', $invoiceFile);
    $zip->addFromString('PDFs/third.pdf', $tsFile);
    $zip->close();
    
    $mail->addAttachment($attachmentArchiveFilename, 'InvoicePDFs.zip');
    
    # be sure to unlink/delete/remove your temporary file
    unlink( $attachmentArchiveFilename );
    
hunteke
  • 3,648
  • 1
  • 7
  • 17