为什么此代码无法使用PHP Zend_Pdf库在PDF上居中显示文本? [英] Why is this code to center text on a PDF using the PHP Zend_Pdf Library not working?
问题描述
我正在尝试在服务器上动态创建PDF文档,并使用Zend_Pdf库将其发送给客户端. PDF上的所有文本都必须与页面居中对齐,页面大小应为字母大小,横向.使用我在各种站点上多次发现的功能时,我遇到了一个问题-中心对齐不正确.所有文本都显示在左侧太远的位置.这是我的代码:
I'm attempting to dynamically create PDF documents on the server and send them to the client using the Zend_Pdf library. All text on the PDF needs to be center aligned to the page, which will be letter-sized, landscape. Using functions that I have found multiple times on various sites, I'm having a problem - the center justification is off. All text is appearing way too far to the left. Here is my code:
<?
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;
}
?>
...这就是结果.
推荐答案
万一其他人遇到类似问题,问题就在这里:
In case anyone else runs into a similar problem, the issue is here:
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;
}
在构建字符数组时,字符加载不正确-8位而不是16位.
When building the characters array, the characters are being loaded incorrectly - 8 bits, not 16.
$characters[] = ord ($drawing_text[$i]);
这可以解决问题,并正确计算文本宽度.
This solves the problem, and correctly calculates text width.
这篇关于为什么此代码无法使用PHP Zend_Pdf库在PDF上居中显示文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!