我正在尝试在服务器上动态创建PDF文档,并使用Zend_Pdf库将它们发送到客户端. PDF上的所有文本都需要与页面居中对齐,页面将是字母大小的横向.使用我在不同网站上多次发现的功能,我遇到了问题 – 中心理由是关闭的.所有文字都显得太偏左了.这是我的代码:
- <?
- require('Zend/Pdf.PHP');
- $font = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA);
- $pdf = new Zend_Pdf();
- // Create a new page,add to page listing
- $pdfPage = $pdf->newPage(Zend_Pdf_Page::SIZE_LETTER_LANDSCAPE);
- $pdf->pages[] = $pdfPage;
- // Add certify that
- $pdfPage->setFont($font,15.75);
- drawCenteredText($pdfPage,"THIS IS TO CERTIFY THAT",378);
- // Add name
- $pdfPage->setFont($font,39.75);
- drawCenteredText($pdfPage,"Example Name",314.25);
- // Headers
- header("Content-type: application/pdf");
- header("Content-Disposition: inline; filename=\"cert.pdf\"");
- header('Content-Transfer-Encoding: binary');
- header('Accept-Ranges: bytes');
- // Output PDF
- echo $pdf->render();
- function drawCenteredText($page,$text,$bottom) {
- $text_width = getTextWidth($text,$page->getFont(),$page->getFontSize());
- $Box_width = $page->getWidth();
- $left = ($Box_width - $text_width) / 2;
- $page->drawText($text,$left,$bottom,'UTF-8');
- }
- function getTextWidth($text,$font,$font_size) {
- $drawing_text = iconv('','UTF-8',$text);
- $characters = array();
- for ($i = 0; $i < strlen($drawing_text); $i++) {
- $characters[] = (ord($drawing_text[$i++]) << 8) | ord ($drawing_text[$i]);
- }
- $glyphs = $font->glyphNumbersForCharacters($characters);
- $widths = $font->widthsForGlyphs($glyphs);
- $text_width = (array_sum($widths) / $font->getUnitsPerEm()) * $font_size;
- return $text_width;
- }
- ?>
……这就是结果.
如果其他人遇到类似的问题,问题在这里:
- function getTextWidth($text,$text);
- $characters = array();
- for ($i = 0; $i < strlen($drawing_text); $i++) {
- $characters[] = (ord($drawing_text[$i++]) << 8) | ord ($drawing_text[$i]);
- }
- $glyphs = $font->glyphNumbersForCharacters($characters);
- $widths = $font->widthsForGlyphs($glyphs);
- $text_width = (array_sum($widths) / $font->getUnitsPerEm()) * $font_size;
- return $text_width;
- }
构建字符数组时,字符加载错误 – 8位,而不是16位.
- $characters[] = ord ($drawing_text[$i]);
这解决了问题,并正确计算文本宽度.