Create PDF & Mail Attachment in Zend Framework

Zend has a library of classes for managing web functionality with various CRUD methods. The two I’m going to focus on today are Zend_Pdf() and Zend_Mail(). By combining these we can create PDF documents on the fly and attach them to emails. I’m going to use a very basic example to demonstrate this. I have also put the code into two functions to keep them separate.

Create PDF

The first thing we’re going to do is build a new PDF document which I have called ‘document.pdf’. I have commented throughout the function to describe each step.

public function createPdf()
{
	// create instance of Zend_Pdf()
	$pdf = new Zend_Pdf();
	// set new page, page size and font
	$page = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_A4);
	$font = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA);
	$page->setFont($font, 12);

	try
	{
		// add content to the PDF
		$page->drawText("Hello world...", 30, 800);
		// add current page to pages array
		$pdf->pages[] = $page;
		// save the document
		$pdf->save('document.pdf');
	
	} catch (Zend_Pdf_Exception $e) {
		// log $e->getMessage() error
	} catch (Exception $e) {
		// log $e->getMessage() error
	}

	// return document contents to be mailed
	return $pdf->render();
}

Attach PDF to Email

The next step is to attach the newly created PDF to your Zend mail function. I’ve commented each step for clarity.

public function sendMail()
{
	// create instance of Zend_Mail()
	$mail = new Zend_Mail();
	// create PDF to send
	$pdf = $this->createPdf();
	
	// attach PDF and set MIME type, encoding and disposition data to handle PDF files
	$attachment = $mail->createAttachment($pdf);
	$attachment->type = 'application/pdf';
	$attachment->disposition = Zend_Mime::DISPOSITION_ATTACHMENT;
	$attachment->encoding = Zend_Mime::ENCODING_BASE64;
	$attachment->filename = 'document.pdf';
	
	// set basic email data including sender, receiver, message and subject line
	$mail->setBodyHtml("Your doument is attached");
	$mail->setFrom('me@mydomain.com', 'The Sender');
	$mail->addTo('you@mydomain.com', 'The Receiver');
	$mail->setSubject('A document for you');
	
	// send email
	$mail->send();	
}

The end result is a document which gets created on the fly and attached to an email, before being sent to the receiver.

Any platform built on top of the Zend framework (such as Magento) can use the classes mentioned above. In a recent project I used it to create a prescription when an order is placed, and have it emailed to the GP pre-filled with the patient’s details.

For more information check out the Zend documentation on Zend_Mail and Zend_Pdf.