How to attach a PDF using DOMPDF in email in laravel - php

Hi i am trying to attach a pdf directly to an email without storing to storage using laravel mail function and sending it to the user. Everything is working fine as expected but the problem is the pdf instead of an attachment is coming as base64 encoded email content.
Can anyone please tell me what i am doing wrong?
Here is my code . This is inside mailer
$subject ='Hello! Your invoice is here';
$data['invoice_id']=$this->content['invoice_id'];
$pdf = PDF::loadView('frontend.pages.invoice.invoice',$data);
return $this->from('info#examplecompany.com')
->subject($subject)
->view('backend.emailtemplates.invoiceEmail')
->attachData($pdf->output(),'name.pdf', [
'mime' => 'application/pdf',
]) ;
I am following this How to attach a PDF using barryvdh/laravel-dompdf into an email in Laravel thread, even though i did the same way as its answer suggest , still not working.
Can anyone please help me on this.
Thank you.

Recommend to use this package for pdf.
https://github.com/niklasravnsborg/laravel-pdf
you can easily manage your pdf export:
output(): Outputs the PDF as a string.
save($filename): Save the PDF to a file
download($filename): Make the PDF downloadable by the user.
stream($filename): Return a response with the PDF to show in the browser.

I think you want to send pdf as an attachment in your email without saving it in your system .
your can refer the following code to do this .
$data["email"]='useremail#gmail.com';
$data["client_name"]='user_name';
$data["subject"]='sending pdf as attachment';
//Generating PDF with all the post details
$pdf = PDF::loadView('userdata'); // this view file will be converted to PDF
//Sending Mail to the corresponding user
Mail::send([], $data, function($message)use($data,$pdf) {
$message->to($data["email"], $data["client_name"])
->subject($data["subject"])
->attachData($pdf->output(), 'Your_Post_Detail.pdf', [
'mime' => 'application/pdf',
])
->setBody('Hi, welcome user! this is the body of the mail');
});
hope it helped you .
for better understanding you can follow this article
how to send pdf as an attachment in email in laravel

Related

Send pdf in attachment (Laravel Mail)

I have this code to get some HTML stored in the column "content" of the "badges" table in a pdf:
$pdf = app()->make('dompdf.wrapper');
$pdf->loadHTML($badgeContent->badge->content);
Do you know if is possible to send this pdf in a attachment using Laravel Mail?
You could sent almost any file in attachment
in laravel, create a new mailable
inside build paste this code
public function build()
{
return $this->view('emails.orders.shipped')
->attach('/path/to/file');
}
If you need more information on this check laravel's documentation
(this code is copied from the laravel's documentation
https://laravel.com/docs/5.6/mail#writing-mailables

Phpmailer add PDF attachment from a link

I'm using PHPMailer to send automatic email (obviously using PHP as programming language).
I would like to add a PDF attachment generated with TCPdf.
Unfortunately I cannot generate the PDF inside the php page where I'm using PHPMailer, and I cannot create a function that generate it.
I can only use a link to generate it, like this:
www.mypage.com/app-pdf/link_generate_pdf.php?IDToGenerate=131&PDFOutput=I
I was thinking that I can recall the page with the PDFOutput=S and "return" in some way the text of the PDF and add it as attachment.
Otherwise I can call the page with PDFOutput=F and save it to a temp folder and then attach it to the email.
The problem is that I don't know how to "call" a page as it were a function and return what the recalling page actually returns.
Do you have some suggestion?
Thank you
edit: I now understand the problem! The problem is that the URL is accessible only from autentication (login page). I thought that as I was logged in, the script was automatically capable of read the page. How can I solve this?
Use this to save the file on the server first and then attach
file_put_contents("Tmpfile.pdf", fopen("http://example.com/file.pdf", 'r'));
Attach as
$mail->AddAttachment('path_to_pdf/Tmpfile.pdf', $name = 'Name_of_pdf_file',
$encoding = 'base64', $type = 'application/pdf');
Hope this helps
Edit: Try this. works fine over here
file_put_contents("path_to_pdf/Tmpfile.pdf",
file_get_contents("http://example.com/file.pdf"));

TCPDF Laravel Email Attachments

TCPDF doesn't seem to be working well with either $dest option ("E" or "S") for sending PDF attachments in Laravel 5.1. Files are always corrupt with an error upon launching Acrobat Reader (error message: ... for example, it was sent as an email attachment and wasn't correctly decoded). Decoding seems ok when I try another PDF generator like DOMPDF.
$pdf = new \TCPDF('P', 'in', 'LETTER', true, 'UTF-8', false);
$pdf->WriteHTML(view('emails.receipt_pdf', $receipt_data));
$attachment = $pdf->Output('Receipt - '.date("M-d-Y").'.pdf','E');
Mail::queue('emails.receipt_email', $receipt_data, function($message) use ($email, $attachment)
{
$message->from('no-reply#website.com')
->to($email)
->subject('Receipt')
->attachData($attachment, 'Receipt.pdf');
});
Just use "S" option while generating pdf. Email-related things will be done by Laravel.
Update
$attachment = $pdf->Output('Receipt - '.date("M-d-Y").'.pdf','E');
to
$attachment = $pdf->Output('Receipt - '.date("M-d-Y").'.pdf','S');
Additionally, if you are using queue() instead of send(), it will fail because of the attachment. To queue, write a job and send with the job queue.

PHP - tcpdf and wamp server

I'm having really a hard time with TCPDF, in what I am seeing from my searching here in Stack Overflow, I can't find any help in understanding on how to use TCPDF. I can't figure out on how to include tcpdf in my website unlike FPDF, I'll just have to copy paste required folders and files inside the folder of the website then place a require(fpdf.php); in the pages. How do I do that in TCPDF?
I can't even figure out how to connect to my database unlike FPDF.
I want to know the basics in understanding TCPDF.
Can someone guide me in understanding TCPDF?
I have used this DOMPDF tutorial to convert my HTML file into PDF. You can send this PDF file to user mail also. It is very easy to understand. Try this and please let me know whether it help you or not. You can see demo here
EDIT :- If you don't want to send a mail then just remove the following code from form.php
// Load the SwiftMailer files
require_once($dir.'/swift/swift_required.php');
$mailer = new Swift_Mailer(new Swift_MailTransport()); // Create new instance of SwiftMailer
$message = Swift_Message::newInstance()
->setSubject('How To Create and Send An HTML Email w/ a PDF Attachment') // Message subject
->setTo(array($post->email => $post->name)) // Array of people to send to
->setFrom(array('no-reply#net.tutsplus.com' => 'Nettuts+')) // From:
->setBody($html_message, 'text/html') // Attach that HTML message from earlier
->attach(Swift_Attachment::newInstance($pdf_content, 'nettuts.pdf', 'application/pdf')); // Attach the generated PDF from earlier
// Send the email, and show user message
if ($mailer->send($message))
$success = true;
else
$error = true;

DOMPDF - attach created PDF to email

What is the easiest way to attach a PDF to an email via DOMPDF?
The end of my script I am using (part of it) is below:
$dompdf = new DOMPDF();
$dompdf->load_html($html);
$dompdf->render();
//below to save the pdf file - not needed if emailing pdf
file_put_contents('/home/ststrave/public_html/pdf/STS_Brochure.pdf', $dompdf->output());
//below to open pdf in browser - required
$dompdf->stream("STS_Brochure_".rand(10,1000).".pdf", array("Attachment" => false));
jexit();
Just for clarification - this is being used in Joomla.
Appreciate the simplest/quickest way using standard PHP mail function.
Cheers ;-)
Ok. You already accepted an answer, but for anyone else coming here, I think there is an easier way, but it's also not PHP's standard mail function, which really isn't going to work. If you can get the pear packages Mail and Mail_mime, it's really easy to send emails with attachments. You can also directly attach the DomPDF output without creating a file, like so:
$dompdf = new DOMPDF();
$dompdf->load_html($html);
$dompdf->set_paper("letter", "portrait" );
$dompdf->render();
$output = $dompdf->output();
$mm = new Mail_mime("\n");
$mm->setTxtBody($body);
$mm->addAttachment($output,'application/pdf','output.pdf', false);
$body = $mm->get();
$headers = $mm->headers(array('From'=>$from,'Subject'=>$subject));
$mail =& Mail::factory('mail');
if($mail->send($to,$headers,$body)){
echo "Your message has been sent.";
}
Here is the solution I was looking for when I came here:
Instead of:
$dompdf->stream();
do this:
$fileatt = $dompdf->output();
And than send mail using PHPMailer and attach the pdf to mail like so:
$filename = 'MyDocument.pdf';
$encoding = 'base64';
$type = 'application/pdf';
$mail->AddStringAttachment($fileatt,$filename,$encoding,$type);
In this way you don't have to deal with saving the file on the server.
PHP's mail function has no "standard" file attachment method. It's an extremely barebones interface to the SMTP system that forces you to do ALL the work of attaching a file yourself.
I strongly suggest using PHPMailer or Swiftmailer to do the email for you - it reduces the heavy grunt work of generating your own MIME email and inserting the attachment (many many lines of code) does to maybe 5 lines total.
Note that neither of them will handle a streamed PDF from DOMPDF. You'll have to save the PDF to a temporary file and attach that,
Raw Data Attachments
The attachData method may be used to attach a raw string of bytes as an attachment. For example, you might use this method if you have generated a PDF in memory and want to attach it to the email without writing it to disk. The attachData method accepts the raw data bytes as its first argument, the name of the file as its second argument, and an array of options as its third argument:
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->view('emails.orders.shipped')
->attachData($this->pdf, 'name.pdf', [
'mime' => 'application/pdf',
]);
}

Categories