通过使用php转换html来下载pdf文件

时间:2014-03-21 09:09:39

标签: php html codeigniter pdf

我正在尝试创建一个电子商务网站,用户将点击该链接,它将开具发票,并应在客户端下载我在html中创建的发票的pdf文件,事情是我使用这个代码,它使用ms字作为.doc文件,但我想做同样的pdf不工作,代码粘贴在下面      // the code to download invoice as word document, it's working <?php header('Content-type: application/vnd.ms-word'); header('Content-Disposition: attachment;Filename='.$result->tracking_number.'.doc'); ?> <!DOCTYPE html> <html> <head>

但与此代码相同不适用于pdf :(

<?php
    header('Content-type: application/pdf');
    header('Content-Disposition: attachment;Filename='.$result->tracking_number.'.pdf');
?>
<!DOCTYPE html>
<html>
<head>

下载的PDF表示格式已损坏,该怎么办,我必须尽快完成:((

1 个答案:

答案 0 :(得分:0)

<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
function pdf_create($html, $filename='', $stream=TRUE) 
{
    require_once("dompdf/dompdf_config.inc.php");

    $dompdf = new DOMPDF();
    $dompdf->load_html($html);
    $dompdf->render();
    if ($stream) {
        $dompdf->stream($filename.".pdf");
    } else {
        return $dompdf->output();
    }
}
?>

4) use it in your controllers like this

<?php
function pdf()
{
     $this->load->helper(array('dompdf', 'file'));
     // page info here, db calls, etc.     
     $html = $this->load->view('controller/viewfile', $data, true);
     pdf_create($html, 'filename');
     or
     $data = pdf_create($html, '', false);
     write_file('name', $data);
     //if you want to write it to disk and/or send it as an attachment    
}
?>

https://github.com/EllisLab/CodeIgniter/wiki/PDF-generation-using-dompdf