简体   繁体   中英

How do I download generated PDF in CodeIgniter 3?

I generated a pdf file in my project using TCPDF but how do I create a function so that when you press the download button it will download the generated pdf.

Here is my Code in controller:

  private function generate_pdf($report){
        require_once APPPATH.'libraries/tcpdf/tcpdf.php';
        $pdf = new TCPDF('P', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

        // set header and footer fonts
        $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
        $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

        // set default monospaced font
        $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

        // set margins
        $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
        $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
        $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);


         // set auto page breaks
        $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

        // set image scale factor
        $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

        // set some language-dependent strings (optional)
        if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
            require_once(dirname(__FILE__).'/lang/eng.php');
            $pdf->setLanguageArray($l);
        }

        foreach ($report as $r) {
            $pdf->AddPage();
            $pdf->writeHTMLCell(0, 0, '', '', $r, 0, 1, 0, true, '', true);
        };

       $pdf->Output('Online Result.pdf', 'D');
    }

And here is the function that downloads the pdf:

public function download_pdf(){
        $this->load->helper('download');
        $data = "";
        $name ="Result.pdf" ;
        force_download($name, $data);
    }

Change your controller method generate_pdf from private to public and at end of the method change to code to follow.

.....
$pdfFile = '<path/to/where/file/is/stored>/Online Result.pdf';
$pdf->Output($pdfFile, 'D');

// force download
$this->load->helper('download');

//Contents of PDF file will be automatically read
force_download($pdfFile, null); 

} // Method end


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM