gpt4 book ai didi

zend-framework - 如何使用 Zend_PDF 正确对齐文本?

转载 作者:行者123 更新时间:2023-12-04 17:24:07 24 4
gpt4 key购买 nike

我正在使用 Zend_PDF。我自己无法弄清楚的唯一任务是将我的文本与页面右侧对齐。

我怎样才能做到这一点?

编辑

我使用下面的 draw010 答案以及在网上找到的其他信息来创建一个新类,我用它来水平对齐文本。

<?php
/**
* Advanced PDF functionnalities
*/
class Advanced_Pdf
{
/**
* Align text at left of provided coordinates
*/
const TEXT_ALIGN_LEFT = 'left';

/**
* Align text at right of provided coordinates
*/
const TEXT_ALIGN_RIGHT = 'right';

/**
* Center-text horizontally within provided coordinates
*/
const TEXT_ALIGN_CENTER = 'center';

/**
* Extension of basic draw-text function to allow it to horizontally center text
*/
public function drawTextWithPosition(Zend_Pdf_Page $page, $text, $y1, $xOffset = 0, $position = self::TEXT_ALIGN_LEFT, $encoding = null)
{
$bottom = $y1; // could do the same for vertical-centering
$text_width = $this->getTextWidth($text, $page->getFont(), $page->getFontSize());

switch ($position) {
case self::TEXT_ALIGN_LEFT:
$left = 60 + $xOffset;
break;
case self::TEXT_ALIGN_RIGHT:
$left = $page->getWidth() - $text_width - $page->getFontSize() - 35 + $xOffset;
break;
case self::TEXT_ALIGN_CENTER:
$left = ($page->getWidth() / 2) - ($text_width / 2) + $xOffset;
break;
default:
throw new Exception("Invalid position value \"$position\"");
}

// display multi-line text
foreach (explode(PHP_EOL, $text) as $i => $line) {
$page->drawText($line,$left,$y1,$encoding);
}
return $this;
}

/**
* Return length of generated string in points
*
* @param string $string
* @param Zend_Pdf_Resource_Font $font
* @param int $font_size
* @return double
*/
public function getTextWidth($text, Zend_Pdf_Resource_Font $font, $font_size)
{
$drawing_text = iconv('', 'UTF-16BE', $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;
}
}
?>

最佳答案

使用来自 this answer 的代码,您可以根据字体和字号计算要绘制的文本的宽度。一旦你有了字符串的宽度,你就可以根据页面的宽度来右对齐它。

$text = 'Some text to right align';
$textWidth = getTextWidth($text, $zendPdfFont, $fontSize);

$page->drawText($text,
$page->getWidth() - $textWidth - $fontSize,
$verticalPosition);

与居中类似:
$page->drawText($text,
($page->getWidth() / 2) - ($textWidth / 2),
$verticalPosition);

关于zend-framework - 如何使用 Zend_PDF 正确对齐文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13269897/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com