因项目需要,现在想在服务器端动态生成PDF文件,已一个PDF为模板,然后把所需的数据动态填入。
本来在使用zend framework,因此很直接的就使用zend_pdf类来进行测试,代码实现如下:
$pdf = Zend_Pdf::load($this->view->config->offline->template);
$pdf->pages = array_reverse($pdf->pages);
$style = new Zend_Pdf_Style();
$font = Zend_Pdf_Font::fontWithPath($this->view->config->offline->font, ( Zend_Pdf_Font::EMBED_DONT_SUBSET));
$pdf->pages[0]->setFont($font, 10);
$pdf->pages[0]->saveGS();
//datalist
$pdf->pages[0]->drawText(str_replace(";","\n",$datalist), 100, 570,"UTF-8");
//project
$pdf->pages[0]->drawText($formData['project'], 100, 430,"UTF-8");
$pdf->pages[0]->drawText($formData['realname'], 100, 78,"UTF-8");
$pdf->pages[0]->drawText($formData['realname'], 130, 590,"UTF-8");
$pdf->pages[0]->drawText($formData['unit'], 95, 58,"UTF-8");
$pdf->pages[0]->drawText($formData['address'], 285, 58,"UTF-8");
$pdf->pages[0]->drawText($formData['postcode'], 470, 58,"UTF-8");
$pdf->pages[0]->drawText($formData['email'], 95, 40,"UTF-8");
$pdf->pages[0]->drawText($formData['phone'], 295, 40,"UTF-8");
$t=getdate();
$pdf->pages[0]->drawText($t['year'], 465, 40,"UTF-8");
$pdf->pages[0]->drawText($t['mon'], 500, 40,"UTF-8");
$pdf->pages[0]->drawText($t['mday'], 525, 40,"UTF-8");
$pdf->pages[0]->restoreGS();
$fn=$formData['realname'].date('YmdHis').".pdf";
$pdf->save($this->view->config->offline->savepath."/".$fn);
这样,的确能完成要求,但是令人恼火的是,其把中文字体内嵌到PDF文件中去,因此导致PDF文件过大,而且导致PHP所需内存也增大(64M)。
因此,就开始尝试别的办法,开始锁定fpdf,PHP能完美支持,而且也能支持中文(所要单独下载chinese.php和chinese-unicode.php)。
但是,FPDF不支持打开已有的PDF文件作为模板,因此还需要使用fpdi进行模板的支持,还要修改fpdi,使其父类为PDF-UNICODE。
然后就可以这样使用:
$pagecount = $this->setSourceFile($this->template);
$tplidx = $this->importPage(1, '/MediaBox');
$this->addPage();
$this->useTemplate($tplidx);
$this->AddUniGBhwFont('ugb','AdobeSongStd-Light-Acro');$this->SetFont('ugb','',$this->fontsize);
$this->setXY(45,65);
$this->Write($this->fontsize,$this->data['realname']);
其中,字形由默认的AdobeSongStd-Light改成AdobeSongStd-Light-Acro,是为了防止英文字体变宽和变窄,格式才会整齐,英文字不会挤在一起。(参考: http://bbs.erp100.com/thread-18424-1-1.html)
发表回复