用PHP生成PDF文件及Label

最近在做的Drupal平臺的Volunteer Management System有個需求,是生成Volunteer的Named Label,來打印成生日卡片。因爲用戶在Named Label上面顯示的信息不確定,所以最好利用現有的組件(如圖),根據搜索結果來生成卡片。

 

當前的VMS Search功能

最初有想過直接生成網頁,並且有做了類似的CSS+div實現。效果很好,但發現了一個問題:用戶在打印的時候,分頁問題無法處理。

 

 

於是我利用一個現有的PDF library,來用PHP生成PDF。

用的PDF library是TCPDF(http://www.tcpdf.org/)。他的功能很齊全,支持把CSS formmated HTML文件轉化成PDF。有很多現成的例子(http://www.tcpdf.org/examples.php)。

 

於是,我用Table的格式來生成卡片(因爲tcpdf目前對於div的width支持還不是很好,所以只能用table的形式來生成)

 

關於向PDF文件中插入HTML的代碼,可以參考example code 61(http://www.tcpdf.org/examples/example_059.phps)。注意到,如果需要自己換頁(比如你有一個table,自動換頁會把這個table切成兩半),每次addPage()之後在插入HTML的時候,需要重新include一次css的內容(在<style></style>tag內的)

 

此外,動態生成table的邏輯有點點複雜。我這裏的情況是,cell需要的內容保存在了一個array裏面,在loop through這個array的時候,生成四格一行、6行一頁的PDF文件。

 

代碼如下:

 

 

    // define some HTML content with style
    $style = <<<EOF
    <style>
    table{
        text-align:center;
        vertical-align:top;
        border-spacing: 20px;
    }
    tr,td{
        margin: 2px;
        border: 2px solid black;
    }
    td{
        padding: 10px
    }
    </style>
EOF;

// Parts to generate tr and td -- make it 4 td per tr
    $cellPerRow = 4; $rowPerPage = 6;
    $counter = 1;
    
    $output = $style."<table>";
    foreach($tableCell as $cell){
        if((($counter - 1) % $cellPerRow) == 0) $output .= "<tr>";
        
        $output.= "<td>";
        foreach($cell as $line){
            $output .= "<p>".$line."</p>";
        }
        $output.= "</td>";
        
        if(($counter % $cellPerRow) == 0) $output .= "</tr>";
        
        if(($counter % ($rowPerPage * $cellPerRow)) == 0){
            $output .= "</table>";
            //drupal_set_message("<pre>".print_r($output,true)."</pre>");
            $pdf->AddPage();
            $pdf->writeHTML($output);
            $output = $style."<table>";
        }
        $counter++;
    }
    
    if($counter % $cellPerRow != 0) $output .= "</tr>";
    if($counter % ($cellPerRow * $rowPerPage) == 0){
        $output .= "</table>";
        //drupal_set_message("<pre>".print_r($output,true)."</pre>");
        $pdf->AddPage();
        $pdf->writeHTML($output);
    } 

    // output the HTML content

 

發佈了5 篇原創文章 · 獲贊 1 · 訪問量 2838
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章