thomaSmith thomaSmith - 16 days ago 12
PHP Question

Is it possible to generate and send a pdf file via email without saving the pdf file locally or on a server

I am generating a pdf file using fpdf, the file contains headings and the corresponding user input from a form which is collected using the post method. I am wanting to attach this pdf to an email so it can be sent to the user. I am going to use phpMailer to do this. I am wondering is it possible to give the pdf a name so it can be attached to the email, but the pdf is not saved on the server or on the users local computer.

the code below loops through the headers array and the form data. then it writes it to a pdf. I have attracted a static pdf file to the attachment parameter, this was just to test if the pdf file sends via email.

code

<?php
require('fpdf.php');
require_once('mail/class.phpmailer.php');
?>
<?php


if(isset($_POST['submit'])) {


$pdf = new FPDF();
$pdf->AddPage();


$headers = ['first name', 'last name'];

$i = 0;

foreach($_POST as $k => $v) {
if($k == 'submit') continue;


$pdf->SetFont('Arial','B',16);
$pdf->write(40,$headers[$i++]);
$pdf->ln(10);
$pdf->write(40,"$v");
$pdf->ln(10);
$content = $pdf->Output('doc.pdf','F');
}
//$bodytext ='jdjdjdjdjd';
//$email = new PHPMailer();
//$email->From = 'example@hotmail.co.uk';
//$email->FromName = 'example';
//$email->Subject = 'PDF AddAttachment';
//$email->Body = $bodytext;
//$email->AddAddress( 'destination@hotmail.co.uk' );

//$file_to_attach = 'file/my.pdf';

//$email->AddAttachment( $file_to_attach , 'my.pdf' );

//return $email->Send();

//$pdf->Output();

}
?>

Answer

FPDF has a output function, which can generate the encoded String. See http://www.fpdf.org/en/doc/output.htm

And PHPMailer can add Attachments from Strings.

So its

$content = $pdf->Output('S');
$email->addStringAttachment($content, 'my.pdf');

That simple.