我正在尝试在服务器上动态创建 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, $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 位。
$characters[] = ord ($drawing_text[$i]);
这解决了问题,并正确计算文本宽度。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)