I have been trying to put interesting issues on my blog instead of documenting them. This has a few advantages, such as I can share my ideas and explain how I solve issues and I can also listen to what other developers have to say. Plus, I can help someone if they’re having a similar problem. So now, let’s get to the problem…
If you work with BLOB data type, you might need to create a .pdf file on the fly and e-mail or download it. Let’s see how I did that. The code should be self-explanatory, but I commented where it’s necessary. If you have any questions, just e-mail me or post a comment here.
FYI, I did this on CakePHP
class YourcontrollerController extends AppController { var $name = 'Yourcontroller'; var $components = array('Email', 'RequestHandler'); /* * Just need to download as PDF * from BLOB data type? */ function get_pdf($id = null) { /* * Say, you have a table name requests * and it has a field name called pdf (blob type) * So our model will be Request */ if (!empty($id)) { $this->Request->recursive = -1; $data = $this->Request->findById($id); $pdf = $data['Request']['pdf']; header('Content-Type: application/pdf'); header('Content-Disposition: attachment; filename=Report.pdf'); echo($pdf); exit; } } /* * We will call this method to save our * generated pdf file on a file direcotry, * lets call it "pdf" */ function upload_pdf($id=null) { if (!empty($id)) { $this->Request->recursive = -1; $data = $this->Request->findById($id); $pdf = $data['Request']['pdf']; $file_name = date('Y-m-d') . $id . "_report.pdf"; $path = ROOT . DS . 'app' . DS . 'webroot' . DS . 'pdf' . DS; $result = file_put_contents($path . $file_name, $pdf); } } /* * Now send the email */ function email() { /* * Generate PDF and save */ $this->upload_pdf($id); $email_to = $receiver_email_address; $html = 'Pdf is attached'; $this->Email->from = '< your_email_address >\You Company'; $this->Email->to = $email_to; $this->Email->subject = "Report"; $this->Email->sendAs = 'html'; /* * Attach the PDF */ $file_name = date('Y-m-d') . $id . "_report.pdf"; $this->Email->attachments = array( ROOT . DS . 'app' . DS . 'webroot' . DS . 'pdf' . DS . $file_name, $file_name => ROOT . DS . 'app' . DS . 'webroot' . DS . 'pdf' . DS . $file_name ); $this->Email->send("<div>$html</div>"); }

