html2pdf.js icon indicating copy to clipboard operation
html2pdf.js copied to clipboard

send generated pdf as an email attachment

Open nauman555 opened this issue 8 years ago • 15 comments

Hi, I am using this API to generate PDF and successfully generating. Is it possible to send the generated PDF as an email attachment using PHP instead of downloading? I have been searching , but wouldnt be able to find any solution

nauman555 avatar Nov 21 '18 07:11 nauman555

This issue is this library uses Javascript which generates the PDF, after its generated it does not save it on the server this works only on the client.

To make this feature work you would have to generate a PDF on the server, and send it on the server side instead of using Javascript to generate a PDF.

Alternatively if you really want to send it using this library, you would have to send a email using javascript on the frontend which might leave it vulnerable to alterations, and everybody could send a email using javascript.

I dont think this might be the library to create and send PDF's

cablegunmaster avatar Nov 22 '18 10:11 cablegunmaster

@cablegunmaster Thankyou. I found a solution for this.

nauman555 avatar Nov 22 '18 11:11 nauman555

How did you handle it ? If I may ask?

cablegunmaster avatar Nov 22 '18 11:11 cablegunmaster

@cablegunmaster generated base64 from pdf object then send it to server and decode and attach with email.

nauman555 avatar Nov 22 '18 11:11 nauman555

Hi @nauman555, glad you found a solution. For anyone else looking here, to get the PDF encoded as a string:

html2pdf().from(element).toPdf().output('datauristring').then(function (pdfAsString) {
    // The PDF has been converted to a Data URI string and passed to this function.
    // Use pdfAsString however you like (send as email, etc)! For instance:
    console.log(pdfAsString);
});

However, if you are doing steps on the server already, I would strongly recommend using wkhtmltopdf instead of html2pdf, it is a lot more stable and is built for server-side solutions. html2pdf's strength is that it is purely client-side.

Closing this issue since @nauman555 said it's resolved, thanks!

eKoopmans avatar Jan 10 '19 09:01 eKoopmans

@eKoopmans Thankyou , your code really helped me alot 💯 👍

nauman555 avatar Jan 10 '19 09:01 nauman555

@eKoopmans How do i get back the pdf file from pdfAsString? Sending it via email just results in corrupt pdf.

bmbariah avatar May 21 '19 07:05 bmbariah

Hi @bmbariah, in general usage if you just want the PDF file you wouldn't use this approach - you would do something like:

html2pdf().from(element).save();

But if there is a reason you have converted the jsPDF object to a data URI string, and want to later retrieve it as a file, there are a few options:

  1. Create a blob with the data URI (example 1 example 2), and/or optionally convert that blob into a File object (example)

  2. Create an anchor tag with the data URI as the href, and either have the user click on it or hide it and automate the click, e.g.:

    // As a test, try using:
    // dataURI = 'data:text/plain;base64,YWFhYWFhYQ=='
    // extension = '.txt';
    var anchor = document.createElement('a');
    anchor.href = dataURI;
    anchor.download = 'file' + extension;
    anchor.click();
    

eKoopmans avatar May 21 '19 10:05 eKoopmans

For anyone interested in sending a PDF as attachment in email I'm sharing the relevant a piece of code that takes care of this - A Wordpress solution.

JS:

let el = document.getElementById('content');
let opt = {
	margin:       1,
	filename:     'myfile.pdf',
	image:        { type: 'jpeg', quality: 1 },
	html2canvas:  { scale: 2 },
	jsPDF:        { unit: 'in', format: 'A4', orientation: 'portrait' }
};

html2pdf().set( opt ).from( el ).toPdf().output('datauristring').then(function( pdfAsString ) {
	let data = {
		'action': 'send_email_with_pdf',
		'fileDataURI': pdfAsString,
	}
	$.post( ajaxobj.ajaxurl, data, function( response ) {
		console.log( response );
	} );
} );

PHP:

function send_email_with_pdf() {
    $pdfdoc		= $_POST['fileDataURI'];
    $b64file 		= trim( str_replace( 'data:application/pdf;base64,', '', $pdfdoc ) );
    $b64file		= str_replace( ' ', '+', $b64file );
    $decoded_pdf	= base64_decode( $b64file );
	file_put_contents( $attachment, $decodPdf );
	
	$mail = new PHPMailer;
	$mail->setFrom( 'YOUR_EMAIL_ADDRESS', 'YOUR_NAME' );
	$mail->addAddress( 'TO_EMAIL_ADDRESS', 'TO_NAME' );
	$mail->Subject  = 'First PHPMailer Message';
	$mail->Body     = 'Hi! This is my first e-mail sent through PHPMailer.';
	$mail->addAttachment( $attachment );
	$mail->isHTML( true );
	if( !$mail->send() ) {
		$response = 'Message was not sent.';
		$response .= 'Mailer error: ' . $mail->ErrorInfo;
	}
	else {
		$response = 'Message has been sent.';
	}

	wp_send_json( $response );
}
add_action( 'wp_ajax_send_email_with_pdf', 'send_email_with_pdf' );
add_action( 'wp_ajax_nopriv_send_email_with_pdf', 'send_email_with_pdf' );

EDIT: You can also use wp_mail() since it's using PHPMailer.

odedta avatar Jun 16 '19 14:06 odedta

I spent 2 days just trying to figure sending by mail, above code didn't work (but send I'm right direction) for me as well as stack-overflow suggestions so I will post here my working code hopefully its helpful to someone. Its uses PHPMailer and can be used with html2canvas to send picture by just changing the type and extension of the file. (im using .onload and setTimeout because im generating PDF on opening the page, this can be removed).

Cheers

JS:

document.getElementById("myPdf").onload = function() {pdfDivload()};	
setTimeout( function pdfDivload (){
let el = document.getElementById('printableArea');
let opt = {
	margin:       1,
	filename:     'myfile.pdf',
	image:        { type: 'jpeg', quality: 0.98 },
	html2canvas:  { scale: 1 },
	jsPDF:        { unit: 'in', format: 'A4', orientation: 'portrait' }
};

html2pdf().set( opt ).from( el ).toPdf().output('datauristring').then(function( pdfAsString ) {
	let data = {
		'fileDataURI': pdfAsString,
	};
	$.post( "../mail.php", data);
	//console.log( data );
} );
}, 3000);

PHP:

$pdfdoc  = $_POST['fileDataURI'];
$b64file        = trim( str_replace( 'data:application/pdf;base64,', '', $pdfdoc ) );
    $b64file        = str_replace( ' ', '+', $b64file );
    $decoded_pdf    = base64_decode( $b64file );

    $mail = new PHPMailer;
    $mail->setFrom( '[email protected]', 'from' );
    $mail->addAddress( [email protected]);
    $mail->Subject  = 'Subject';
    $mail->Body     = 'body text';
    $mail->addStringAttachment($decoded_pdf, "nalog.pdf");
    $mail->isHTML( false );
    $mail->send();

ikiK-CRO avatar Apr 25 '20 14:04 ikiK-CRO

@eKoopmans

I have tried to use the method used by @ikiK-CRO with my laravel application. I tried to convert my html dom into pdf and send that pdf as an attachment with email.

I am using Vue2 in frontend along with html2pdf.js. I am using this to download the dom as pdf and sending the pdf as email attachment. The pdf which is directly downloading is opening correctly but the pdf I am receiving on email is unable to open showing error Failed to load pdf document on chrome and unable to open document , File type plain text document (text/plain) is not supported.

This is my html2pdf code on frontend:

let opt = {
   margin:       1,
   filename:     'summary.pdf',
   image:        { type: 'jpeg', quality: 0.98 },
   html2canvas:  { scale: 2 },
   jsPDF:        { unit: 'in', format: 'A4', orientation: 'portrait' }
};

let canvas = document.querySelector("#summary-block");

html2pdf().from(canvas).toPdf()
.output('datauristring')
.then(function (pdfAsString) {
    const data = {
        pdf: pdfAsString,
        emails: this.emails
    }
    console.log("promise-2-1");
    console.log(this.selectedListing);
    HTTP.post(`api/listings/${this.selectedListing.id}/share`, data)
    .then((response) => {
        this.btnLoading = false;
        this.tagError = false;
        this.emails = [];
    })

}.bind(this));

This is my php code in my Laravel controller.

$request = $this->request;
$b64file = trim( str_replace( 'data:application/pdf;base64,', '', $request->pdf ) );
$b64file = str_replace( ' ', '+', $b64file );
$decoded_pdf = base64_decode( $b64file );

if(!empty($request->emails))
{
    foreach ($request->emails as $recipient)
    {
        $user = User::find($recipient["key"]);
        $__NAME__ = 'User';
        $__MAIL_FROM_NAME__ = "Repylot";
        $__ADMIN_EMAIL__ = "[email protected]";
        $search = ['__NAME__', '__MAIL_FROM_NAME__', '__ADMIN_EMAIL__'];
        $replace = [$__NAME__,$__MAIL_FROM_NAME__, $__ADMIN_EMAIL__];
        Mail::to($user)->send(new EmailNotificationWithAttachment($request->pdf, $search, $replace, "offer_summary"));
    }
}

and EmailNotificationWithAttachment have handle

return $this->subject($subject)->html($template)->attachData(
        $attachment, 'summary.pdf', [
        'mime' => 'application/pdf',
    ]);

abhimanusharma avatar Dec 30 '20 10:12 abhimanusharma

@abhimanusharma

Hey make the following changes.

If you look at the fileDataURI string it contains "data:application/pdf;filename=generated.pdf;base64," but the code is trying to replace "data:application/pdf;base64," so change it to "data:application/pdf;filename=generated.pdf;base64,".

Also you can remove this line "$b64file = str_replace( ' ', '+', $b64file );" there is no need for it.

you can also verify the base64 string on this site "https://base64.guru/tools/repair" to make sure its correct it will also tell you what to remove.

RayazSookoo avatar Jan 15 '21 18:01 RayazSookoo

@RayazSookoo Thank you so much. This resolved the problem. Steps I took to resolve are. First I replaced data:application/pdf;base64, with data:application/pdf;filename=summary.pdf;base64, which still cause error because I don't understand why my base64 hasfilename=generated.pdf so I did as it is mentioned by RayazSookoo. All other code is same as before.

abhimanusharma avatar Jan 18 '21 04:01 abhimanusharma

Brilliant I have been searching for this solution for many days now Thank you for your site and Examples https://base64.guru/developers/php/examples I can now send an email attachment directly using: 'html2pdf.bundle.min.js' with 'jquery.min.js' post to PHP 'PHPMailer' All i needed to do was to strip "data:application/pdf;filename=generated.pdf;base64," out from the string before sending to PHP Thank you Thank you Regards Ulrich

ulrichcbosman avatar May 22 '22 10:05 ulrichcbosman

I sought a solution for ages and eventually found the answer https://hypertexter.space/questions/unable-to-transform-webpage-into-a-html-email-format I needed

webpack-mergebrennan avatar Feb 01 '25 22:02 webpack-mergebrennan