How to create pdf and mail it in codeigniter

To create a PDF and mail it in CodeIgniter, you can use the following steps:

Step 1: Install the necessary libraries

You'll need to install the following libraries:

You can install them using Composer:

composer require tcpdf/tcpdf
composer require swiftmailer/swiftmailer

Step 2: Create a PDF using TCPDF

Create a new PHP file (e.g., generate_pdf.php) and add the following code:

<?php

require_once APPPATH. 'third_party/tcpdf/tcpdf.php';

class Generate_pdf extends TCPDF {

    public function __construct() {
        parent::__construct();
        $this->setPaper('A4', 'portrait');
        $this->setFontSize(12);
    }

    public function generate_pdf($data) {
        $this->addPage();
        $this->writeHTML($data);
        $this->Output('example.pdf', 'I');
    }
}

This code creates a TCPDF object and sets the paper size and font size. The generate_pdf method takes an array of data as input and writes it to the PDF file.

Step 3: Create a PDF using the generated data

Create a new PHP file (e.g., create_pdf.php) and add the following code:

<?php

require_once 'generate_pdf.php';

$data = array(
    'heading' => 'Hello World',
    'content' => 'This is a sample PDF'
);

$pdf = new Generate_pdf();
$pdf->generate_pdf($data);

?>

This code creates a new instance of the Generate_pdf class and calls the generate_pdf method, passing the $data array as input.

Step 4: Send the PDF as an attachment via email using SwiftMailer

Create a new PHP file (e.g., send_email.php) and add the following code:

<?php

require_once APPPATH. 'third_party/swiftmailer/swift_required.php';

$mailer = Swift_Mailer::newInstance();

$message = Swift_Message::newInstance('PDF Attachment')
    ->setFrom(array('[email protected]' => 'Your Name'))
    ->setTo(array('[email protected]' => 'Recipient Name'))
    ->setBody('This is a sample email')
    ->attach(Swift_Attachment::fromPath('example.pdf'));

$mailer->send($message);

?>

This code creates a new SwiftMailer object and sends an email with the generated PDF as an attachment.

Step 5: Call the send_email.php file

In your CodeIgniter controller, call the send_email.php file to send the email:

<?php

class My_controller extends CI_Controller {

    public function send_pdf() {
        $this->load->library('email');
        $this->email->set_newline("\r\n");
        $this->email->from('[email protected]', 'Your Name');
        $this->email->to('[email protected]', 'Recipient Name');
        $this->email->subject('PDF Attachment');
        $this->email->message('This is a sample email');
        $this->email->attach('example.pdf');
        $this->email->send();
    }
}

This code loads the email library, sets the email parameters, and sends the email with the generated PDF as an attachment.

That's it! You should now be able to create a PDF and send it as an attachment via email using CodeIgniter.