thinkphp整合系列之tcpdf類生成pdf文件

php生成pdf文件的需求是不怎麼常見的;當然也是有的;

既然已經整合使用了;那就寫篇博客來講解下吧;

示例項目:http://git.oschina.net/shuaibai123/thinkphp-bjyadmin

一:引入tcpdf

/ThinkPHP/Library/Vendor/Tcpdf

把tcpdf整個目錄拷到自己的項目中;

二:函數

/Application/Common/Common/function.php

/**
 * 生成pdf
 * @param  string $html      需要生成的內容
 */
function pdf($html='<h1 style="color:red">hello word</h1>'){
    vendor('Tcpdf.tcpdf');
    $pdf = new \Tcpdf(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
    // 設置打印模式
    $pdf->SetCreator(PDF_CREATOR);
    $pdf->SetAuthor('Nicola Asuni');
    $pdf->SetTitle('TCPDF Example 001');
    $pdf->SetSubject('TCPDF Tutorial');
    $pdf->SetKeywords('TCPDF, PDF, example, test, guide');
    // 是否顯示頁眉
    $pdf->setPrintHeader(false);
    // 設置頁眉顯示的內容
    $pdf->SetHeaderData('logo.png', 60, 'baijunyao.com', '白俊遙博客', array(0,64,255), array(0,64,128));
    // 設置頁眉字體
    $pdf->setHeaderFont(Array('dejavusans', '', '12'));
    // 頁眉距離頂部的距離
    $pdf->SetHeaderMargin('5');
    // 是否顯示頁腳
    $pdf->setPrintFooter(true);
    // 設置頁腳顯示的內容
    $pdf->setFooterData(array(0,64,0), array(0,64,128));
    // 設置頁腳的字體
    $pdf->setFooterFont(Array('dejavusans', '', '10'));
    // 設置頁腳距離底部的距離
    $pdf->SetFooterMargin('10');
    // 設置默認等寬字體
    $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
    // 設置行高
    $pdf->setCellHeightRatio(1);
    // 設置左、上、右的間距
    $pdf->SetMargins('10', '10', '10');
    // 設置是否自動分頁  距離底部多少距離時分頁
    $pdf->SetAutoPageBreak(TRUE, '15');
    // 設置圖像比例因子
    $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
    if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
        require_once(dirname(__FILE__).'/lang/eng.php');
        $pdf->setLanguageArray($l);
    }
    $pdf->setFontSubsetting(true);
    $pdf->AddPage();
    // 設置字體
    $pdf->SetFont('stsongstdlight', '', 14, '', true);
    $pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true);
    $pdf->Output('example_001.pdf', 'I');
}

三:使用方法

好吧;這個沒什麼好說的了;全寫註釋裏面了;

更多栗子:/ThinkPHP/Library/Vendor/Tcpdf/examples

需要註明的就是:

  1. 可以寫html標籤的;比如說是識別h標籤的字體加粗加大效果的;

  2. 可以寫style樣式;但是並不能完全支持;

  3. tcpdf的官網需要自帶***:http://www.tcpdf.org

白俊遙博客


本文爲白俊遙原創文章,轉載無需和我聯繫,但請註明來自白俊遙博客http://baijunyao.com                        

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章