Обтекание текста в Fpdf в Php

Я пытаюсь обернуть текст в ячейку, используя FPDF. вот мой код.

<?php require('fpdf.php'); $pdf = new FPDF(); $pdf->AddPage(); $pdf->SetFont('Arial','',16); $pdf->Cell(20,7,'Hi1',1); $pdf->Cell(20,7,'Hi2',1); $pdf->Cell(20,7,'Hi3',1); $pdf->Ln(); $pdf->Cell(20,7,'Hi4',1); $pdf->Cell(20,7,'Hi5(xtra)',1); $pdf->Cell(20,7,'Hi5',1); $pdf->Output(); ?> 

Результат для этого кода выглядит так: введите описание изображения здесь

Теперь я хочу обернуть этот текст Xtra, который есть в Cell. Текст xtra должен перейти во вторую строку. Как мне это сделать.

когда я использую MultiCell для этой строки $ pdf-> MultiCell (20, 7, «Hi5 (xtra)», 1); Это меняется на следующее. введите описание изображения здесь

Я пробовал ответ, упомянутый Log1c. Он вышел таким образом введите описание изображения здесь

Используйте MultiCell() вместо Cell()

Измените это:

 $pdf->Cell(20,7,'Hi5(xtra)',1); 

Для того, чтобы:

 $pdf->MultiCell( 20, 7, 'Hi5(xtra)', 1); 

MultiCell () используется для печати текста с несколькими строками.

РЕДАКТИРОВАТЬ:

Я вижу, что MultiCell() разбивает линию, поэтому новая ячейка будет помещена ниже текущей позиции.

В таком случае вы можете рассчитать координаты x и y и вычислить новую позицию и установить позицию после вывода каждой ячейки.

 <?php require('fpdf.php'); $pdf = new FPDF(); $pdf->AddPage(); $start_x=$pdf->GetX(); //initial x (start of column position) $current_y = $pdf->GetY(); $current_x = $pdf->GetX(); $cell_width = 20; //define cell width $cell_height=7; //define cell height $pdf->SetFont('Arial','',16); $pdf->MultiCell($cell_width,$cell_height,'Hi1',1); //print one cell value $current_x+=$cell_width; //calculate position for next cell $pdf->SetXY($current_x, $current_y); //set position for next cell to print $pdf->MultiCell($cell_width,$cell_height,'Hi2',1); //printing next cell $current_x+=$cell_width; //re-calculate position for next cell $pdf->SetXY($current_x, $current_y); //set position for next cell $pdf->MultiCell($cell_width,$cell_height,'Hi3',1); $current_x+=$cell_width; $pdf->Ln(); $current_x=$start_x; //set x to start_x (beginning of line) $current_y+=$cell_height; //increase y by cell_height to print on next line $pdf->SetXY($current_x, $current_y); $pdf->MultiCell($cell_width,$cell_height,'Hi4',1); $current_x+=$cell_width; $pdf->SetXY($current_x, $current_y); $pdf->MultiCell($cell_width,$cell_height,'Hi5(xtra)',1); $current_x+=$cell_width; $pdf->SetXY($current_x, $current_y); $pdf->MultiCell($cell_width,$cell_height,'Hi5',1); $current_x+=$cell_width; $pdf->SetXY($current_x, $current_y); $pdf->Output(); ?> 

Я не думаю, что Multicell – это решение для этого. Проблемы с использованием многоразового использования.

  • разрывы строк введите описание изображения здесь
  • перекрывается следующая строка введите описание изображения здесь
  • Более того, мы не можем предсказать, сколько высоты может пройти клетка? например: если первая длина текста ячейки равна 50, а вторая длина текста равна 100, то ее высота отличается, поэтому мы не можем создать ее в виде строки таблицы.

    Даже вышеприведенный ответ помогает решить только разрыв линии, но не проблему перекрытия.

Здесь я пришел с новым решением для этой функции. Новая функция vcell () использует только ячейку в ней для успешного вывода ожидаемого результата.

 <?php require('fpdf.php'); class ConductPDF extends FPDF { function vcell($c_width,$c_height,$x_axis,$text){ $w_w=$c_height/3; $w_w_1=$w_w+2; $w_w1=$w_w+$w_w+$w_w+3; $len=strlen($text);// check the length of the cell and splits the text into 7 character each and saves in a array if($len>7){ $w_text=str_split($text,7); $this->SetX($x_axis); $this->Cell($c_width,$w_w_1,$w_text[0],'','',''); $this->SetX($x_axis); $this->Cell($c_width,$w_w1,$w_text[1],'','',''); $this->SetX($x_axis); $this->Cell($c_width,$c_height,'','LTRB',0,'L',0); } else{ $this->SetX($x_axis); $this->Cell($c_width,$c_height,$text,'LTRB',0,'L',0);} } } $pdf = new ConductPDF(); $pdf->AddPage(); $pdf->SetFont('Arial','',16); $pdf->Ln(); $x_axis=$pdf->getx(); $c_width=20;// cell width $c_height=6;// cell height $text="aim success ";// content $pdf->vcell($c_width,$c_height,$x_axis,'Hi1');// pass all values inside the cell $x_axis=$pdf->getx();// now get current pdf x axis value $pdf->vcell($c_width,$c_height,$x_axis,'Hi2'); $x_axis=$pdf->getx(); $pdf->vcell($c_width,$c_height,$x_axis,'Hi3'); $pdf->Ln(); $x_axis=$pdf->getx(); $c_width=20; $c_height=12; $text="aim success "; $pdf->vcell($c_width,$c_height,$x_axis,'Hi4'); $x_axis=$pdf->getx(); $pdf->vcell($c_width,$c_height,$x_axis,'Hi5(xtra)'); $x_axis=$pdf->getx(); $pdf->vcell($c_width,$c_height,$x_axis,'Hi5'); $pdf->Ln(); $x_axis=$pdf->getx(); $c_width=20; $c_height=12; $text="All the best"; $pdf->vcell($c_width,$c_height,$x_axis,'Hai'); $x_axis=$pdf->getx(); $pdf->vcell($c_width,$c_height,$x_axis,'VICKY'); $x_axis=$pdf->getx(); $pdf->vcell($c_width,$c_height,$x_axis,$text); $pdf->Ln(); $x_axis=$pdf->getx(); $c_width=20; $c_height=6; $text="Good"; $pdf->vcell($c_width,$c_height,$x_axis,'Hai'); $x_axis=$pdf->getx(); $pdf->vcell($c_width,$c_height,$x_axis,'vignesh'); $x_axis=$pdf->getx(); $pdf->vcell($c_width,$c_height,$x_axis,$text); $pdf->Output(); ?> 

введите описание изображения здесь

Описание функции:

 function vcell($c_width,$c_height,$x_axis,$text){ $w_w=$c_height/3; $w_w_1=$w_w+2; $w_w1=$w_w+$w_w+$w_w+3; // $w_w2=$w_w+$w_w+$w_w+$w_w+3;// for 3 rows wrap $len=strlen($text);// check the length of the cell and splits the text into 7 character each and saves in a array if($len>7){ $w_text=str_split($text,7);// splits the text into length of 7 and saves in a array since we need wrap cell of two cell we took $w_text[0], $w_text[1] alone. // if we need wrap cell of 3 row then we can go for $w_text[0],$w_text[1],$w_text[2] $this->SetX($x_axis); $this->Cell($c_width,$w_w_1,$w_text[0],'','',''); $this->SetX($x_axis); $this->Cell($c_width,$w_w1,$w_text[1],'','',''); //$this->SetX($x_axis); // $this->Cell($c_width,$w_w2,$w_text[2],'','','');// for 3 rows wrap but increase the $c_height it is very important. $this->SetX($x_axis); $this->Cell($c_width,$c_height,'','LTRB',0,'L',0); } else{ $this->SetX($x_axis); $this->Cell($c_width,$c_height,$text,'LTRB',0,'L',0);} } 

вы используете пространство между словами, если оно не будет содержать пробел, оно останется таким, как есть … попробуйте следующее

 <?php require('fpdf.php'); $pdf = new FPDF(); $pdf->AddPage(); $pdf->SetFont('Arial','',16); $pdf->Cell(20,7,'Hi1',1); $pdf->Cell(20,7,'Hi2',1); $pdf->Cell(20,7,'Hi3',1); $pdf->Ln(); $pdf->Cell(20,7,'Hi4',1); $pdf->Cell(20,7,'Hi5 (xtra)',1); $pdf->Cell(20,7,'Hi5',1); $pdf->Output(); ?> 

наслаждаться 🙂

Я пробую все это решение, но смотрю его таблицу строк. поэтому я пробую это решение и его помощь мне так много,

 $pdf=new PDF_MC_Table(); $pdf->AddPage(); $pdf->SetFont('Arial','',14); //Table with 20 rows and 4 columns $pdf->SetWidths(array(30,50,30,40)); srand(microtime()*1000000); for($i=0;$i<20;$i++) $pdf->Row(array("test","test testtesttesttest ","test","test testtesttesttest ")); $pdf->Output(); 

ссылка : FPDF

Я столкнулся с той же проблемой и попытался найти способ наличия или отсутствия ячейки для текста и разделить высоту на количество строк и использовать результат как для конкретной высоты ячейки. Но это делает код очень сложным. затем я перехожу в библиотеку под названием html2pdf. Он создает html-таблицу, в которой нет какого-либо вышеупомянутого конфликта, и эта страница конвертируется в файл pdf. Используйте библиотеку html2pdf .. это самый простой способ создания PDF с автоматически разделенной ячейкой. вы можете скачать его здесь, и в Интернете есть множество путеводителей.

Попробуйте следующее: вы можете передавать ширину столбцов, выравнивание столбцов, заливки и ссылки в виде массивов. если ширина – это число, это будет ширина всей таблицы.

 <?php require('fpdf.php'); class PDF extends FPDF{ function plot_table($widths, $lineheight, $table, $border=1, $aligns=array(), $fills=array(), $links=array()){ $func = function($text, $c_width){ $len=strlen($text); $twidth = $this->GetStringWidth($text); $split = floor($c_width * $len / $twidth); $w_text = explode( "\n", wordwrap( $text, $split, "\n", true)); return $w_text; }; foreach ($table as $line){ $line = array_map($func, $line, $widths); $maxlines = max(array_map("count", $line)); foreach ($line as $key => $cell){ $x_axis = $this->getx(); $height = $lineheight * $maxlines / count($cell); $len = count($line); $width = (isset($widths[$key]) === TRUE ? $widths[$key] : $widths / count($line)); $align = (isset($aligns[$key]) === TRUE ? $aligns[$key] : ''); $fill = (isset($fills[$key]) === TRUE ? $fills[$key] : false); $link = (isset($links[$key]) === TRUE ? $links[$key] : ''); foreach ($cell as $textline){ $this->cell($widths[$key],$height,$textline,0,0,$align,$fill,$link); $height += 2 * $lineheight * $maxlines / count($cell); $this->SetX($x_axis); } if($key == $len - 1){ $lbreak=1; } else{ $lbreak = 0; } $this->cell($widths[$key],$lineheight * $maxlines, '',$border,$lbreak); } } } } $pdf = new PDF('P','mm','A4'); $lineheight = 8; $fontsize = 12; $pdf->SetFont('Arial','',$fontsize); $pdf->SetAutoPageBreak(true , 30); $pdf->SetMargins(20, 1, 20); $pdf->AddPage(); $table = array(array('Hi1', 'Hi2', 'Hi3'), array('Hi4', 'Hi5 (xtra)', 'Hi6'), array('Hi7', 'Hi8', 'Hi9')); $widths = array(11,11,11); $pdf->plot_table($widths, $lineheight, $table); $pdf->Output('Table.pdf', 'I'); return; 

Следует нарисовать это: таблица FPDF