I am looking at the ablity for users to enter some information into a form and send it via mail()
.
What I'd like is for the details to be sent as a PDF attachment. Possibly with the name of the the sender and a date/time. test_user_06052011.pdf
I have a design for the PDF, but I'm not sure how I'd integrate this design to create a PDf in PHP.
Does anyone have an examples or ways in which I could do this?
A good idea when sending important documents such as a resume via email attachment or a link is to send them as PDFs. The PDF is a great format for professional correspondence because it's universal, versatile and accessible.
Open your email (Eg: Outlook) and simply click 'New Email' on the ribbon bar to open a new message window. Now, go to 'Insert > Object > Create from File' and browse the PDF file that you need to insert in the body of your email message and click ok.
Very easy way to create PDF server-site is using wkhtmltopdf. However, you will need a shell access to server to set it up.
To create PDF you need two files: one is PHP which generates HTML you want to convert into PDF. Let's say this is invoice.php:
<?php
$id = (int) $_GET['id'];
?>
<h1>This is invoice <?= $id ?></h1>
<p>some content...</p>
And the other one, which will fetch the invoice and convert it into PDF using wkhtmltopdf:
<?php
$tempPDF = tempnam( '/tmp', 'generated-invoice' );
$url = 'http://yoursite.xx/invoice.php?id=123';
exec( "wkhtmltopdf $url $tempPDF" );
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename=invoice.pdf');
echo file_get_contents( $tempPDF );
unlink( $tempPDF );
Once you have created a PDF file you can also send mail with attachment this way:
<?php
$to = "[email protected]";
$subject = "mail with attachment";
$att = file_get_contents( 'generated.pdf' );
$att = base64_encode( $att );
$att = chunk_split( $att );
$BOUNDARY="anystring";
$headers =<<<END
From: Your Name <[email protected]>
Content-Type: multipart/mixed; boundary=$BOUNDARY
END;
$body =<<<END
--$BOUNDARY
Content-Type: text/plain
See attached file!
--$BOUNDARY
Content-Type: application/pdf
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="your-file.pdf"
$att
--$BOUNDARY--
END;
mail( $to, $subject, $body, $headers );
Can't find reason for using native mail()
function today. In mostly trivial situations we can use PHPMailer library, which in OOP style gives us opportunity to send emails even without understanding of header.
The solution even without saving physical file is
$mail = new PHPMailer();
...
$doc = $pdf->Output('S');
$mail->AddStringAttachment($doc, 'doc.pdf', 'base64', 'application/pdf');
$mail->Send();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With