Codeigniter how to create PDF

Codeigniter how to create PDF

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Codeigniter How to Create PDF

Building an invoice system in CodeIgniter requires a solid strategy for generating PDFs, especially when the output needs to be attached to emails. The core challenge is ensuring the final document looks consistent across different operating systems and email clients without forcing users to interact with their printers or rely on external drivers. While printing to PDF is a viable option for internal archiving, it introduces significant friction for end-users who simply want a digital file they can forward immediately.

The most robust approach for modern web applications is HTML-to-PDF conversion. Instead of trying to render a complex PDF from scratch using low-level libraries, you generate a clean HTML template with CSS and then convert that string into a PDF file on the server side. This method leverages the rendering engines built into browsers (like wkhtmltopdf or Chrome/Headless) to produce high-quality output that respects your layout rules.

CodeIgniter itself does not include a native PDF generation library, which means you will need to integrate an external tool. The industry standard for this task is usually wkhtmltopdf. You install the binary on your server and then call it via a shell command from within your PHP script.

Here is how you might structure a controller method in CodeIgniter to handle this:

// app/controllers/Invoices.php
public function generate($id) {
    // Fetch invoice data from MySQL
    $this->load->model('Invoice_model');
    $data = $this->invoice_model->get($id);
    
    // Load the view which returns HTML string
    ob_start();
    $this->load->view('invoices/print_view', $data);
    $html = ob_get_clean();
    
    // Execute wkhtmltopdf conversion
    $pdf_path = '/path/to/invoices/invoice_' . $id . '.pdf';
    $command = "wkhtmltohtml --javascript-delay 1000 --enable-local-file-access -";
    
    // Note: Implementation varies by version. 
    // Common usage is passing the HTML string or file directly.
    // If using a binary that accepts stdin:
    exec($command . ' > "' . $pdf_path . '"', $output, $return_var);
    
    if ($return_var === 0) {
        // Send email with attachment
        $this->load->library('email');
        $config = array(
            'protocol' => 'smtp',
            // ... other config
        );
        
        $this->email->set_to('client@example.com');
        $this->email->subject('Invoice #'. $id);
        $this->email->message($html); // Send HTML email body
        
        if ($this->email->send()) {
            return redirect()->back()->with('success', 'Invoice sent.');
        }
    } else {
        return redirect()->back()->with('error', 'PDF generation failed.');
    }
}

One of the biggest pitfalls in this workflow is handling CSS compatibility. Not all CSS properties supported by browsers translate perfectly to PDF rendering engines. You must strip out unsupported styles or use specific print-friendly CSS classes. Additionally, wkhtmltopdf can be tricky with complex JavaScript or dynamic content that requires loading external assets; you often need to configure the binary to allow local file access or embed images directly into the HTML string before conversion.

An alternative is to generate a Microsoft Word document using ODBC or similar connectors and let the user handle the export. While this avoids server-side dependencies like wkhtmltopdf, it relies on the client having Office installed and configured correctly. It also opens up security concerns regarding file execution if the server is not hardened properly.

For a production invoice system, the HTML-to-PDF route offers the best balance of quality and automation. You get pixel-perfect control over the layout in your view files, and the conversion happens silently on the backend. If you find yourself needing more advanced PDF manipulation features later, such as merging documents or adding digital signatures directly into the stream, you might consider switching to a PHP-native library like TCPDF or DomPDF. These libraries are heavier but allow for pure PHP logic without spawning external processes.

Regardless of the engine you choose, remember that email attachments can be tricky with certain providers due to file size limits and MIME type restrictions. Always test your generated PDFs by sending them through various email clients (Gmail, Outlook, Apple Mail) to ensure they render as expected before rolling out the system.

Our network