Creating a PDF on Air and Send as Attachment

| By Webner

How to create a PDF on air (in a variable) and sending it as an email attachment?

Problem:- I need to create a PDF and send it as an attachment with email but I don’t have permission to write a new PDF file on any folder of the server.

Solution:- I found a solution for this to use TCPDF library to generate a PDF from the HTML and store it in a variable as we store a PDF in file on a physical location. Then use that variable to send it as an attachment with your email.

Step 1:- Download the TCPDF library from this link ->

Step 2:- Copy it in any folder of your project.

Step 3:- include and use this library where you want to generate a PDF or want to send PDF as attachment.

include ($_SERVER ['DOCUMENT_ROOT'] . "/TCPDF-master/tcpdf.php");

$pdf = new TCPDF ( 'P', 'mm', 'Letter' );

$pdf->SetCreator ( "CREATOR NAME" );
$pdf->SetAuthor ( 'AUTHOR NAME' );
$pdf->SetTitle ( 'TITLE' );
$pdf->SetSubject ( 'SUBJECT' );
$pdf->AddPage ( 'P' );
// $pdf->setPrintHeader ( false );
// $pdf->setPrintFooter ( false );
$pdf->WriteHTML ( '[HTML CONTENT]' );

$pdfGenerated = $pdf->Output ( $fileNumber . '.pdf', 'S' );

// S is signal that will tell function to return the pdf as variable. There are some other signals that can be used to download PDF or PDF directly in the browser also.
// Add below written lines to your email body content. $msg variable is the email body content.
$attachment = chunk_split ( base64_encode ( $pdfGenerated ) );

$msg .= $rn . '--' . $boundary . $rn;
$msg .= 'Content-Type: application/pdf; name="Invoice.pdf"' . $rn;
$msg .= "Content-Transfer-Encoding: base64" . $rn;
$msg .= 'Content-ID: <' . $boundary_content . '>' . $rn;

$msg .= $rn . $attachment . $rn . $rn;

mail ( $to, $subject, $msg, $headers );

Leave a Reply

Your email address will not be published. Required fields are marked *