Search code examples
codeigniterpdfdompdf

Dompdf generated pdf is 0 bytes


I am trying to save a pdf to disk.

I am using Dompdf and Codeigniter as below:

$this->load->helper('dompdf','file');
$this->load->helper('file');
$saveTo = './labels'; 
$data['id'] = $this -> uri -> segment(3);
$data['no_of_prints'] = $this -> uri -> segment(4);   
$labelname = "Label". $data['id'] ."-". $data['no_of_prints'] . ".pdf";
$html = $this->load->view('label_view', $data, TRUE);
file_put_contents($saveTo."/".$labelname, pdf_create($html, $labelname));

While the labelname gets generated correctly. The file saved to disk reads 0 bytes and as expected I get an Adobe Reader cannot open this file ... error.

I am also using fancybox 2.0 to popup the pdf and when I right click on the popup,(the pdf does not show, i'm guessing pdf plugin issues) I am able to Save as a readable pdf that is not 0 bytes.

It is important for the application to save pdf to disk automatically. How do i save a readable pdf to disk?


Solution

  • I have found some old CI code (pre version 2) that used DomPDF, I had an extra parameter to write as a file.
    Is this much different from yours?

    <?php if (!defined('BASEPATH')) exit('No direct script access allowed');
    function pdf_create($html, $filename, $stream=FALSE, $orientation='portrait')
    {
        require_once("dompdf/dompdf_config.inc.php");
        spl_autoload_register('DOMPDF_autoload');
    
        $dompdf = new DOMPDF();
        $dompdf->set_paper( array(0,0, 2.175 * 72, 3.375 * 72), "landscape" ); // credit card size
        $dompdf->load_html($html);
        $dompdf->render();
        if ($stream)
        {
            $dompdf->stream($filename.".pdf");
        }
        else
        {
            $CI =& get_instance();
            $CI->load->helper('file');
            write_file("./uploads/$filename.pdf", $dompdf->output());
        }
    }
    ?>