OverSu OverSu - 1 month ago 51
PHP Question

jsPDF, html2canvas, PHPMailer, again...! Attach PDF to mail

I had read a lot of answer about "how to attach PDF via PHPMailer from html2canva or jsPDF", but everything I tried didn't work.

For now, I have an HTML page with some input. When the customer fill all of them, he clicks on Send button.


  • html2canva take a screenshot

  • jsPDF cut it into as page as it needs

  • jQuery send the PDF to a PHP Script

  • PHPMailer takes it and send via mail.



Everything work, except the attachment of the PDF File.

So, I need your help ;)

This is what I have :

JS Script :

html2canvas($("#Div"), {
onrendered: function(canvas) {

//=== Take screenshot
var imgData = canvas.toDataURL('image/jpeg');

//=== PDFize it
var doc = new jsPDF("p", "px");
var options = {
pagesplit: true
};

//=== Split it
var imgWidth = 210;
var pageHeight = 295;
var imgHeight = canvas.height * imgWidth / canvas.width;
var heightLeft = imgHeight;

var doc = new jsPDF('p', 'mm');
var position = 0;

doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
heightLeft -= pageHeight;

while (heightLeft >= 0) {
position = heightLeft - imgHeight;
doc.addPage();
doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
heightLeft -= pageHeight;
}

//=== Send it
$.post("mail.php",
{
data: doc;
}, function () {}).done(function() {/*SOME CODE*/});

//=== Just to test the PDF
doc.save( 'file.pdf');
}
});


And my PHP Script :

<?php

if(!empty($_POST['data']))
{

require 'lib/PHPMailer-master/PHPMailerAutoload.php';
$mail = new PHPMailer;

$mail->isSMTP();
$mail->Host = '*';
$mail->SMTPAuth = *;
$mail->Username = '*';
$mail->Password = '*';
$mail->SMTPSecure = '*';
$mail->Port = *;

$mail->setFrom('*', '*');
$mail->addAddress('*', '*');

//=== Tested this
$originalbase = $base;
//=== or this
$base = explode('data:application/pdf;base64,', $_POST['data']);
$mail->addStringAttachment($originalbase, "name.pdf", "base64", "application/pdf");

$mail->isHTML(true);

$mail->Subject = '*';
$mail->Body = '*';

if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}

} else echo "No Data Found";

?>


I had tested with base64 decode, without, with the mime type, without...

Edit 13.10.2016
Seems to be good with

var PDF = doc.output('datauri');

$base = explode('data:application/pdf;base64,', $_POST['data']);
$base = base64_decode($base[1]);
$mail->addStringAttachment($base, 'pdfName.pdf');

Answer

try this line without the other parameters , if it does not work , can you share a part of the begging of the base64 posted to php

$mail->addStringAttachment($pdfString, 'pdfName.pdf');
Comments