fPDF: как вычеркнуть / зачеркнуть выровненный текст в многоклеточном режиме? - PullRequest
1 голос
/ 14 мая 2010

Я создаю PDF с помощью fPDF.

Мне нужно зачеркнуть длинный текст внутри MultiCell. Текст выровнен по левому и правому краям, что, вероятно, является источником проблемы.

Вот мой код:

//get the starting x and y of the cell to strikeout
$strikeout_y_start = $pdf->GetY();
$strikeout_x = $pdf->getX();
$strikeText = "Some text with no New Lines (\n), which is wrapped automaticly, cause it is  very very very very very very very very very very long long long long long long long long long long long long long long long long long long"
//draw the text
$pdf->MultiCell(180, 4, $strikeText);
//get the y end of cell
$strikeout_y_end = $pdf->GetY();
$strikeout_y = $strikeout_y_start+2;
$strikeCount = 0;
for ($strikeout_y; $strikeout_y < $strikeout_y_end - 4; $strikeout_y+=4) {
    $strikeCount++;
    //strike out the full width of all lines but last one - works OK
    $pdf->Line($strikeout_x, $strikeout_y, $strikeout_x + 180, $strikeout_y);
}

//this works, but gives incorrect results
$width = $pdf->GetStringWidth($strikeText);
$width = $width - $strikeCount*180;
//the line below will strike out some text, but not all the letters of last line
$pdf->line($strikeout_x, $strikeout_y, $strikeout_x+$width, $strikeout_y);

Проблема в том, что, поскольку текст в многоклеточном коде оправдан (и должен быть), пробел в предыдущих строках шире, чем предполагает GetStringWidth, поэтому GetStringWidth недооценивает полную ширину этого текста.

В результате последняя строка обводится, скажем, в 70%, а некоторые буквы в конце не обводятся.

Есть идеи, как рассчитать ширину последней строки в многоклеточном режиме?

Ответы [ 2 ]

3 голосов
/ 14 мая 2010

Я нашел решение сам. Извините, что задали ненужные вопросы.

Вот что я сделал:

class VeraPDF extends FPDF {

    /**
     * Returns width of the last line in a multicell
     * useful for strike out / strike through 
     * 
     *
     * @param string $s - the string measured
     * @param int $lineWidth - with of the cell/line
     * @return int
     */
    function GetStringWidth_JustifiedLastLineWidth($s, $lineWidth)
    {
        //Get width of a string in the current font
        $s=(string)$s;
        $words = split(' ',$s);
        $cw=&$this->CurrentFont['cw'];
        $w=0;
        $spaceWidth = $this->GetStringWidth(' ');

        for($i=0, $wordsCount = count($words); $i<$wordsCount; $i++){
            // sum up all the words width, and add space withs between the words
            $w += $this->GetStringWidth($words[$i]) + $spaceWidth;
            if ($w > $lineWidth) {
                //if current width is more than the line width, then the current word
                //will be moved to next line, we need to count it again
                $i--;
            }
            if ($w >= $lineWidth) {
                //if the current width is equal or grater than the line width, 
                //we need to reset current width, and count the width of remaining text
                $w = 0;
            }
        }
        //at last, we have only the width of the text that remain on the last line!
        return $w;
    }    
}

Надеюсь, это кому-то помогло:)

0 голосов
/ 14 мая 2010

пробел в предыдущих строках шире чем предполагает GetStringWidth, так GetStringWidth недооценивает полную ширина этого текста.

Вы пытались посчитать пробелы и добавить недостающую ширину самостоятельно. Скажем, каждое пространство должно иметь ширину 5 пикселей, но fpdf оценивает его в 4 пикселя, возможно, вы могли бы добавить 1 пиксель на пространство к общей ширине в конце.

...