用PHP生成PDF文件及Label
最近在做的Drupal平台的Volunteer Management System有个需求,是生成Volunteer的Named Label,来打印成生日卡片。因为用户在Named Label上面显示的信息不确定,所以最好利用现有的组件(如图),根据搜索结果来生成卡片。
?
最初有想过直接生成网页,并且有做了类似的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
?