On Sep 24, 2007, at 6:23 AM, ArticSun wrote:

At the moment I need to align text to the right (prices of an invoice all need to align at the right). But how do I do this? I found the following
code:

The function below has a couple of problems:

function get_text_width($text_line,$current_font, $font_size)
{
    $glyph_array = array();
    $total_item_width = 0;
    $text_array = str_split($text_line,1);
    foreach($text_array as $character)
    {
        $glyph_array[] = ord($character);
    }

Glyph indices only rarely map directly to character codes. Depending on the font you are using, this loop will probably return the wrong glyphs for the characters being drawn, causing the width calculation to be incorrect.

   $oPage->drawText($oFont->getUnitsPerEm(), 10, 10);

It is not necessary to draw text on a page to measure its width. This line can be removed.

    $text_width = $current_font->widthsForGlyphs($glyph_array);
    foreach($text_width as $char_width)
    {
        $total_item_width = $total_item_width + $char_width;
    }
    return ($total_item_width/1000)*$font_size;

The built-in 14 PDF fonts all have a 1000 unit-per-em glyph box, but many TrueType fonts use 2048.

}

This seems to do SOMEthing, but if I take the right border at 1000 and I
take the result of the function of this, it still isn't aligned at the
right. It seems like the returned value isn't right.

Does anyone have a suggestion on how to correctly align text items to the
right?

Here's a function you can use to measure the width of a string of text:

/**
* Returns the total width in points of the string using the specified font and
* size.
*
* @param string $string
* @param Zend_Pdf_Resource_Font $font
* @param float $fontSize Font size in points
* @return float
*/
function widthForStringUsingFontSize($string, $font, $fontSize)
{
    $drawingString = iconv('', 'UTF-16BE', $string);
    $characters = array();
    for ($i = 0; $i < strlen($drawingString); $i++) {
$characters[] = (ord($drawingString[$i++]) << 8) | ord ($drawingString[$i]);
    }
    $glyphs = $font->cmap->glyphNumbersForCharacters($characters);
    $widths = $font->widthsForGlyphs($glyphs);
$stringWidth = (array_sum($widths) / $font->getUnitsPerEm()) * $fontSize;
    return $stringWidth;
}

$font = Zend_Pdf_FontFactory::fontWithName (Zend_Pdf_Const::FONT_HELVETICA);
$stringWidth = widthForStringUsingFontSize('Hello world!', $font, 12);


$stringWidth is returned in points. Subtract that value from your right margin to use as the $x coordinate to the $page->drawText() call.

--

Willie Alberty, Owner
Spenlen Media
[EMAIL PROTECTED]

http://www.spenlen.com/

Reply via email to