Проблема с переносом длинного текста с использованием PHP FPDF - PullRequest
0 голосов
/ 08 сентября 2018

enter image description here

У меня есть отчет, как на картинке выше. Текст столбцов заголовка слишком длинный, и я хочу сделать перенос текста на эту ячейку, но он не работает и показывает данные в вертикальных столбцах. Я прочитал документ FPDF .. и пытался много, но все еще не работал, это результат, который я получаю с моим кодом:

enter image description here

что я могу сделать, чтобы обернуть текст первого столбца?

function toPDF($data, $cols = NULL, $cols_event = NULL){
 global $action, $meta;  

if ($cols) {
    // translate column weighting to page width in mm
    $colno = 0;
    $max_col = count($cols);
    foreach ($cols as $col) {
        $colno += $col[0];
    }
    foreach ($cols as $key => $col) {
        $cols[$key][0] = (int)($col[0] / $colno * 196);
    }
} elseif($cols_event){
    $colno = 0;
    $max_col = count($cols_event);
    foreach ($cols_event as $col) {
        $colno += $col[0];
    }
    foreach ($cols_event as $key => $col) {
        $cols[$key][0] = (int)($col[0]);
    }
} else {
    $max_col = 0;
    foreach ($data as $line) {
        if (is_array($line)) $max_col = max(count($line), $max_col);
    }
    $width = $max_col == 0 ? 196 : 196 / $max_col;
    $cols = array();
    for ($cc = 0; $cc < $max_col; $cc++) {
        $cols[] = array($width, "");
    }
}


class PDF extends FPDF{

    function Header()
    {
    }

    function Footer()
    {
        //Go to 1.5 cm from bottom
        $this->SetY(-15);
        //Select Arial italic 8
        $this->SetFont('Arial', 'I', 8);
        //Print centered page number
        $this->Cell(0, 10, 'Page ' . ($this->page . ' of {nb}'), 0, 0, 'C');
    }

}

// $pdf = new PDF('P', 'mm', 'Letter');
$pdf = new PDF('P','mm',array(550,300));
$pdf->SetDisplayMode("real", "continuous");
$pdf->AliasNbPages();
$pdf->SetFont('Arial', '', 10);
$pdf->SetTextColor(0);
$pdf->SetDrawColor(200, 200, 200);
$pdf->SetFillColor(255, 255, 255);
$pdf->SetLineWidth(.1);
$pdf->SetLeftMargin(10);
$pdf->AddPage();

$pdf->Cell(190,10, $meta['title'],"B",1,"C",0);

$first = true;
foreach ($data as $line) {
    if (is_array($line)) {
        for ($field = 0; $field < $max_col; $field++) {
            if (isset($line[$field])) {
                if(is_array($line[$field])) {
                    $pdf->Cell($cols[$field][0], 6, strip_tags($line[$field][0]), 1, 0, $cols[$field][1], 1);
                } else {
                    if($first) {
                        $pdf->Cell($cols[$field][0], 6, strip_tags($line[$field]), 1, 0, 'L', 1);
                    } else {
                        $pdf->MultiCell($cols[$field][0], 6, strip_tags($line[$field]));
                    }
                }
            } else {
                $pdf->Cell($cols[$field][0], 6, "", 1, 0, 'L', 1);
            }
        }
    }
    $pdf->Ln(6);
    $first = false;
}

$pdf->Output($action . ".pdf", "I");
}

Ответы [ 2 ]

0 голосов
/ 11 сентября 2018

наконец, я решил проблему, настроив коды из примера FPDF. вот ссылка http://www.fpdf.org/?go=script&id=3.

@ Марко Мессина Спасибо, что вы мне очень помогли

function toPDF($data, $cols = NULL){
global $action, $meta;

if ($cols) {
    // translate column weighting to page width in mm
    $colno = 0;
    $max_col = count($cols);
    foreach ($cols as $col) {
        $colno += $col[0];
    }
    foreach ($cols as $key => $col) {
        $cols[$key][0] = (int)($col[0] / $colno * 196);
    }
} else {
    $max_col = 0;
    foreach ($data as $line) {
        if (is_array($line)) $max_col = max(count($line), $max_col);
    }
    $width = $max_col == 0 ? 196 : 196 / $max_col;
    $cols = array();
    for ($cc = 0; $cc < $max_col; $cc++) {
        $cols[] = array($width, "");
    }
}

class PDF extends FPDF{
var $widths;
var $aligns;

    function SetWidths($w){
        //Set the array of column widths
        $this->widths=$w;
    }

    function SetAligns($a){
        //Set the array of column alignments
        $this->aligns=$a;
    }

    function Row($data){
        //Calculate the height of the row
        $nb=0;
        for($i=0;$i<count($data);$i++)
            $nb=max($nb,$this->NbLines($this->widths[$i],$data[$i]));
        $h=5*$nb;
        //Issue a page break first if needed
        $this->CheckPageBreak($h);
        //Draw the cells of the row
        for($i=0;$i<count($data);$i++)
        {
            $w=$this->widths[$i];
            $a=isset($this->aligns[$i]) ? $this->aligns[$i] : 'L';
            //Save the current position
            $x=$this->GetX();
            $y=$this->GetY();
            //Draw the border
            $this->Rect($x,$y,$w,$h);
            //Print the text
            $this->MultiCell($w,5,$data[$i],0,$a);
            //Put the position to the right of the cell
            $this->SetXY($x+$w,$y);
        }
        //Go to the next line
        $this->Ln($h);
    }

    function CheckPageBreak($h){
        //If the height h would cause an overflow, add a new page immediately
        if($this->GetY()+$h>$this->PageBreakTrigger)
            $this->AddPage($this->CurOrientation);
    }

    function NbLines($w,$txt){
        //Computes the number of lines a MultiCell of width w will take
        $cw=&$this->CurrentFont['cw'];
        if($w==0)
            $w=$this->w-$this->rMargin-$this->x;
        $wmax=($w-2*$this->cMargin)*1000/$this->FontSize;
        $s=str_replace("\r",'',$txt);
        $nb=strlen($s);
        if($nb>0 and $s[$nb-1]=="\n")
            $nb--;
        $sep=-1;
        $i=0;
        $j=0;
        $l=0;
        $nl=1;
        while($i<$nb)
        {
            $c=$s[$i];
            if($c=="\n")
            {
                $i++;
                $sep=-1;
                $j=$i;
                $l=0;
                $nl++;
                continue;
            }
            if($c==' ')
                $sep=$i;
            $l+=$cw[$c];
            if($l>$wmax)
            {
                if($sep==-1)
                {
                    if($i==$j)
                        $i++;
                }
                else
                    $i=$sep+1;
                $sep=-1;
                $j=$i;
                $l=0;
                $nl++;
            }
            else
                $i++;
        }
        return $nl;
    }
}    

$pdf = new PDF('P','mm',array(550,500));
$pdf->SetDisplayMode("real", "continuous");
$pdf->AliasNbPages();
$pdf->SetFont('Arial', '', 10);
$pdf->SetTextColor(0);
$pdf->SetDrawColor(200, 200, 200);
$pdf->SetFillColor(255, 255, 255);
$pdf->SetLineWidth(.1);
$pdf->SetLeftMargin(10);
$pdf->AddPage();

$pdf->SetWidths(array(50,25,25,35,35,35,35,35,35,20,10,20,20,10,10,10,10,35,35,35));
$pdf->SetAligns('L');
srand(microtime()*1000000);
for($i=0; $i < count($data); $i++)
$pdf->Row($data[$i]);
$pdf->Output();
}
0 голосов
/ 08 сентября 2018

Эй, я искал решение этой проблемы, я нашел что-то! Я думал, что мы используем в качестве значения разность getY () (до многоклеточного) и getY (после многоклеточного), мы можем установить правильные координаты. Я должен был внести некоторые незначительные изменения, чтобы сделать эту работу.

Единственная проблема, которая сейчас только края. Вместо этого ячейки установлены правильно.

  • Я установил три переменные перед строкой "foreach ($ data as $ line)":

    $ y1 = $ pdf-> GetY ();

    $ i = 1;

    $ y2 = 1;

  • Я изменил фрагмент кода, где у вас был Multicell, с помощью:

                    $pdf->SetLeftMargin(20);                    
                    $x = $pdf->GetX();
    
                    $y = $pdf->GetY();
    
                    $pdf->MultiCell($cols[$field][0], 6, strip_tags($line[$field]), "L T R");
    
                    $y2 = $pdf->GetY();
    
                    $i++;
    
                    if($y2 > $y1 ){
                        $y1 = $y2;  
                    }
    
                    if($i > 5){
                        $pdf->SetXY($x + $cols[$field][0], $y1 - 6);
                        $i = 1;                 
                    }else{
                        $pdf->SetXY($x + $cols[$field][0], $y);
                    }   
    

This is a photo of a test

...