We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Generating PDF file in Phalcon framework

I am using phalcon framework, and i need to generate pdf file. I was thinking to use mpdf library, i serached online and i didn't find how to use mpdf in phalcon for generating pdf files. Please, I need some example of how can i do this , in easiest way. I worked with mpdf in codeigniter, and here is my function example:

    public function createPdf(){
    $userId = $this->input->post('bbb');

    $this->load->model('osoba');
    $this->load->library('pdf');
    $rez['rez'] = $this->osoba->getUsers($userId);
    $html = $this->load->view('pdf_report', $rez, true);
    $pdf = $this->pdf->load();
    $pdf->WriteHTML($html, 2);
    $br = rand(0,100000);
    $ispis = "Pobjeda Rudet-Izvjestaj-".$br;
    $pdf->Output($ispis, 'I');
}

I need to achieve this in Phalcon, please I neeed your help. Thanks in advance.



98.9k

Try this:

public function createPdf()
{
    $this->view->disable();

    $userId = $this->request->getPost('bbb');   

    $rez['rez'] = Users::findFirstById($userId)
    $html = $this->view->getRender('reports', 'pdf_report', $rez);

    $pdf = new mPDF();

    $pdf->WriteHTML($html, 2);
    $br = rand(0, 100000);
    $ispis = "Pobjeda Rudet-Izvjestaj-".$br;

    $pdf->Output($ispis, "I");
}
edited Oct '15

And how do I use mPDF the Phalcon? Because from what I researched, the mPDF does not work with namespace.

True, mPDF live in the global namespace... but it has it's own loader in include("../mpdf.php");, so there's no need to do anything special in Phalcon. Just include that file and define any globals according to the mPDF docs. There shouldn't be any collisions.



13.8k

Hello, I'm facing and issue with Phalcon and mPDF. My code is as follows:

    public function indexAction()
    {
      $this->view->disable();
      $html = '<bookmark content="Start of the Document" /><div>Section 1 text</div>';

      $mpdf = new \Mpdf\Mpdf();
      $mpdf->WriteHTML($html);
      $mpdf->Output();
    }

it outputs an invalid/corrupted PDF file, I can't see it in chrome/firefox.

I'm using latest version at moment, installed via composer as the mPDF docs suggested.

What's wrong?

Try setting up proper headers:

      $this->response->setHeader('Cache-Control', 'max-age=0');
      $this->response->setHeader('Content-Type', 'application/pdf');
      $this->response->setHeader('Content-Disposition', 'attachment; filename="my-file_' . date('Y-m-d') . '.xlsx"');
      $this->view->disable();
      $html = '<bookmark content="Start of the Document" /><div>Section 1 text</div>';
      $mpdf = new \Mpdf\Mpdf();
      $mpdf->WriteHTML($html);
      $mpdf->Output();


13.8k
edited Feb '18

Thanks for reply, Lajos. I find out the way adding exit() after $mpdf->Output(); it feels 'hacky'.

Edit: I just tried your suggestion but didn't work for me :-(