0

Trying to figure out how to send a generated pdf from html2pdf (Javascript - Erik Koopmans) to the phpmailer via Ajax. I can save the document to the local users pc. But I need to be able to attach the generated pdf to an email using phpmailer.

Here's the code where I've managed to generate the pdf document perfectly for saving to the users computer:

// Get div for pdf document
let page = document.getElementById('printPage');

// html2pdf options
var options = {
    margin: [5, 0, 0, 0],
    filename: 'test.pdf',
    image: {
        type: 'jpeg',
        quality: 1
    },
    pagebreak: {
        mode: ['legacy']
    },
    html2canvas: {
        scale: 3
    },
    jsPDF: {
        unit: 'mm',
        format: 'a4',
        orientation: 'portrait'
    }
};

// SAVE DOCUMENT AS PDF
$(document).on('click', '#saveBtn', function() {
    html2pdf().from(page).set(options).save();
});

This works perfectly. Now I just need to figure out how to send this same pdf to phpmailer and attach it to an email.

From what I've read, some people mentioned that I need to somehow use the line:

html2pdf().from(page).set(pdfOptions).toPdf().output('datauristring')

I don't quite understand this. Am I suppose to send it as a string to php? Or is there some better way of doing it? Thanks.

  • You can send it directly as a string value, sure; or create a "pseudo" file upload out of it, if you like that any better (https://stackoverflow.com/a/34340245/1427878) – CBroe May 12 '23 at 06:02

1 Answers1

0

Ok, this was a real fiddly process, but after much digging, I finally got it to work.

//JAVASCRIPT
let page = document.getElementById('printPage');
            
var options = {
    margin: [5, 0, 0, 0],
    filename: 'test.pdf',
    image: {
        type: 'jpeg',
        quality: 1
    },
    pagebreak: {
        mode: ['legacy']
    },
    html2canvas: {
        scale: 3
    },
    jsPDF: {
        unit: 'mm',
        format: 'a4',
        orientation: 'portrait'
    }
};
            
            
let pdfContent;

// get the pdf as a string:
await html2pdf().from(page).set(pdfOptions).outputPdf('datauristring').then(function( pdfAsString ) {
  pdfContent = pdfAsString;
});
            
            
$.ajax({
  type: "POST",
  url: ajaxUrl,
  data: {
      action: "sendEmail",
      transaction: transaction,
      transactionId: transactionId,
      emailTo: $("#emailTo").val(),
      emailCc: $("#emailCc").val(),
      emailBcc: $("#emailBcc").val(),
      emailSubject: $("#emailSubject").val(),
      emailMessage: $("#emailMessage").val(),
      pdfContent: pdfContent
  },
  success: function(data) {
    console.log(data);
  }
});  

And on the PHP side:

$pdfdoc = $_POST['pdfContent'];
$pdfData = substr($pdfdoc, strpos($pdfdoc, ","));
    
    
//Create phpMailer instance:
$mail = new PHPMailer(true);
    
try {
    //Server settings
    $mail->SMTPDebug = 1;
    $mail->isSMTP();
    $mail->Host = 'hostnameGoesHere';
    $mail->SMTPAuth = true;
    $mail->Port = 2525;
    $mail->Username = 'userABC';
    $mail->Password = 'password123';
    
    //Recipients
    $mail->setFrom($companyEmail, 'My Company');
    $mail->addAddress($emailTo);    
    
    //Attachments
    $mail->AddStringAttachment(base64_decode($pdfData), "Test.pdf", "base64", "application/pdf");
    
    
    //Content
    $mail->isHTML(true);
    $mail->Subject = $emailSubject;
    $mail->Body    = $formattedMessage;
    $mail->AltBody = strip_tags($formattedMessage);
    
    $mail->send();
    echo 'Message has been sent';
} catch (Exception $e) {
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}