【问题标题】:Wrap Text in Fpdf in Php在 PHP 中的 Fpdf 中换行文本
【发布时间】:2014-06-25 20:57:32
【问题描述】:

我正在尝试使用 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 文本包装到单元格中。 xtra 文本应进入第二行。我该怎么做。

当我对该行使用 MultiCell 时 $pdf->MultiCell( 20, 7, 'Hi5(xtra)', 1);它正在变成以下..

我已经尝试过 Log1c 提到的答案 它是这样出来的

【问题讨论】:

    标签: php pdf fpdf word-wrap


    【解决方案1】:

    使用MultiCell() 代替Cell()

    改变这个:

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

    收件人:

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

    MultiCell() 用于打印多行文本。

    编辑:

    我可以看到MultiCell() 换行,因此新单元格将被放置在当前位置下方。

    在这种情况下,您可以计算xy 坐标并在输出每个单元格后计算新位置和设置位置。

    <?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();
    ?>
    

    【讨论】:

    • 当我使用了多单元格时,我得到了如上所示的结果-我已经编辑了我的问题,请检查。 Hi5 进入第三排。这不是我想要的。
    • 不确定,但尝试将所有Cell() 更改为MultiCell()
    • 不,它不工作所有都进入下一行。理想情况下,它创建了 6 行和一列。
    • 是的,我试过了。我将编辑我的问题并添加图片,请检查。主单元格“Hi5(Xtra) 将进入下一行,但同时我希望其他两个单元格“Hi4”和“Hi5”也扩展。
    • 因为它们是单独的单元格,内部不是同一行。
    【解决方案2】:

    我不认为 Multicell 是解决这个问题的方法。使用 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 
    
    $lengthToSplit = 7;
    if($len>$lengthToSplit){
    $w_text=str_split($text,$lengthToSplit);
    $this->SetX($x_axis);
    $this->Cell($c_width,$w_w_1,$w_text[0],'','','');
    if(isset($w_text[1])) {
        $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);}
        } 
    

    【讨论】:

    • 这是一个非常棒的解决方案 Vigneswaran。谢谢你。 “w_w”代表什么?宽度_宽度?
    • @JeremyCanfield:它是一个高度。 $w_w=$c_height/3;示例:如果你想用 3 行换行,并且单元格高度为 9,那么 9/3=3。第一个 w_w 行将在高度 3 处回显,下一行将在高度 6 处回显,下一行将在高度 9 处回显。
    • 假设您不知道单元格是否足够,如果需要自动分裂,您究竟是如何提出的..?对于第一个 raw,您将高度硬编码为 6,对于第二个 raw,您将高度硬编码为 12。如果需要自动决定怎么办?
    • @ChanakaSuranga :我给出了一个想法,找到一个根据字符数自动创建高度的函数。然后你的问题解决了:)。自动查找并传递。
    【解决方案3】:

    我尝试了所有解决方案,但它的中断表行外观。 所以我尝试了这个解决方案,它对我帮助很大,

    $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();
    

    reference: FPDF

    【讨论】:

      【解决方案4】:

      这会通过敲击字体大小自动将文本换行到单元格中:

      class FPDF_CellFit extends FPDF
      {
          //Cell with horizontal scaling if text is too wide
          function CellFit($w, $h=0, $txt='', $border=0, $ln=0, $align='', $fill=false, $link='', $scale=false, $force=true)
          {
              //Get string width
              $str_width=$this->GetStringWidth($txt);
      
              //Calculate ratio to fit cell
              if($w==0)
                  $w = $this->w-$this->rMargin-$this->x;
              $ratio = ($w-$this->cMargin*2)/$str_width;
      
              $fit = ($ratio < 1 || ($ratio > 1 && $force));
              if ($fit)
              {
                  if ($scale)
                  {
                      //Calculate horizontal scaling
                      $horiz_scale=$ratio*100.0;
                      //Set horizontal scaling
                      $this->_out(sprintf('BT %.2F Tz ET',$horiz_scale));
                  }
                  else
                  {
                      //Calculate character spacing in points
                      $char_space=($w-$this->cMargin*2-$str_width)/max(strlen($txt)-1,1)*$this->k;
                      //Set character spacing
                      $this->_out(sprintf('BT %.2F Tc ET',$char_space));
                  }
                  //Override user alignment (since text will fill up cell)
                  $align='';
              }
      
              //Pass on to Cell method
              $this->Cell($w,$h,$txt,$border,$ln,$align,$fill,$link);
      
              //Reset character spacing/horizontal scaling
              if ($fit)
                  $this->_out('BT '.($scale ? '100 Tz' : '0 Tc').' ET');
          }
      
          //Cell with horizontal scaling only if necessary
          function CellFitScale($w, $h=0, $txt='', $border=0, $ln=0, $align='', $fill=false, $link='')
          {
              $this->CellFit($w,$h,$txt,$border,$ln,$align,$fill,$link,true,false);
          }
      
          //Cell with horizontal scaling always
          function CellFitScaleForce($w, $h=0, $txt='', $border=0, $ln=0, $align='', $fill=false, $link='')
          {
              $this->CellFit($w,$h,$txt,$border,$ln,$align,$fill,$link,true,true);
          }
      
          //Cell with character spacing only if necessary
          function CellFitSpace($w, $h=0, $txt='', $border=0, $ln=0, $align='', $fill=false, $link='')
          {
              $this->CellFit($w,$h,$txt,$border,$ln,$align,$fill,$link,false,false);
          }
      
          //Cell with character spacing always
          function CellFitSpaceForce($w, $h=0, $txt='', $border=0, $ln=0, $align='', $fill=false, $link='')
          {
              //Same as calling CellFit directly
              $this->CellFit($w,$h,$txt,$border,$ln,$align,$fill,$link,false,true);
          }
      }
      
      
      $text="dfshsdbfhbsdhfbhsdbfkbfkbfkbdf";
         $this->CellFitScale(50,10,'  '.$text,1,0,'',0);//long text
      

      【讨论】:

        【解决方案5】:

        我遇到了同样的问题,并尝试找到一种方法来确定单元格是否足以容纳文本,并将高度除以行数,并将结果用于特定的单元格高度。但是,它只会使代码变得非常复杂。然后我切换到一个名为 html2pdf 的库。它创建没有任何上述冲突的html表,并且该页面转换为pdf文件。 使用 html2pdf 库.. 这是使用自动分割单元格创建 pdf 的最简单方法。 可以here下载,网上有很多教程。

        【讨论】:

          【解决方案6】:

          试试这个: 您可以将列宽、列对齐、填充和链接作为数组传递。如果宽度是一个数字,它将是整个表格的宽度。

          <?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 table

          【讨论】:

            【解决方案7】:

            <?php 
            require "fpdf.php";
            
            $db = new PDO("mysql:host=localhost;dbname=coba","root");
            $id="";
            class myPDF extends FPDF{
                function header(){
                    $this->image('adw1.png',15,10);
            		$this->image('huawei.png',235,13);
                    $this->SetFont('Times','B',14);
                    $this->Cell(276,10,'Berita Acara Barang Keluar',0,0,'C');
                    $this->Ln();		
                    $this->SetFont('Times','B',12);
                    $this->Cell(276,10,'PT ADYAWINSA WEST JAVA',0,0,'C');
                    $this->Ln(20);
            		$this->SetFont('Times','',10);
                    $this->Cell(276,-15,'JL. RUMAH SAKIT NO 108',0,0,'C');
                    $this->Ln(5);
            		$this->Line(10,36,287,36);
            		$this->SetLineWidth(0);
            		$this->Line(10,37,287,37);
            		$this->Ln(5);
            		$this->SetFont('Times','B',8);
            		$this->Cell(8,10,'No',1,0,'C');
            		$this->Cell(20,10,'Tgl Keluar',1,0,'C');
            		$this->Cell(30,10,'Nama Receiver',1,0,'C');
            		$this->Cell(60,10,'Nama Barang',1,0,'C');
            		$this->Cell(15,10,'Bom Code',1,0,'C');
            		$this->Cell(35,10,'Site Name',1,0,'C');
            		$this->Cell(20,10,'Site ID',1,0,'C');
                    $this->Cell(10,10,'Qty',1,0,'C');
            		$this->Cell(10,10,'Unit',1,0,'C');
            		$this->Cell(20,10,'Material Type',1,0,'C');
            		$this->Cell(20,10,'Nama Project',1,0,'C');
            		$this->Cell(30,10,'Keterangan',1,0,'C');
                    $this->Ln();
                }
                function footer(){
                    $this->SetY(-15);
                    $this->SetFont('Arial','',8);
                    $this->Cell(0,10,'Page '.$this->PageNo().'/{nb}',0,0,'C');
            		$this->SetY(140);
                    $this->SetFont('Arial','',10);
                    $this->Cell(100,10,'Receiver',0,0,'C');
            		$this->SetY(140);
                    $this->SetFont('Arial','',10);
                    $this->Cell(0,10,'Verified By',0,0,'C');
            		$this->SetY(140);
                    $this->SetFont('Arial','',10);
                    $this->Cell(450,10,'Approved By',0,0,'C');
            		$this->SetY(160);
                    $this->SetFont('Arial','',10);
                    $this->Cell(100,10,'(.........................)',0,0,'C');
            		$this->SetY(160);
                    $this->SetFont('Arial','',10);
                    $this->Cell(0,10,'(.........................)',0,0,'C');
            		$this->SetY(160);
                    $this->SetFont('Arial','',10);
                    $this->Cell(450,10,'(.........................)',0,0,'C');
                }
                function viewTable($db){
            		$no=1;
            		$id = $_GET['bk_id'];
                    $this->SetFont('Times','',6);
                    $stmt = $db->query("SELECT tgl_keluar, nama_karyawan, barang_nama, bom_code, site_name, site_id, qty, barang_kategori, material_type, nama_project, keterangan from barang_keluar INNER JOIN bk_detail ON barang_keluar.bk_id = bk_detail.bk_id where barang_keluar.bk_id = '$id'");
            		while($data = $stmt->fetch(PDO::FETCH_OBJ))
            		{
            			$this->Cell(8,10,$no++,1,0,'C');
            			$this->Cell(20,10,$data->tgl_keluar,1,0,'C');
            			$this->Cell(30,10,$data->nama_karyawan,1,0,'C');
            			$this->Cell(60,10,$data->barang_nama,1,0,'C');
            			$this->Cell(15,10,$data->bom_code,1,0,'C');
            			$this->Cell(35,10,$data->site_name,1,0,'C');
            			$this->Cell(20,10,$data->site_id,1,0,'C');
                        $this->Cell(10,10,$data->qty,1,0,'C');
            			$this->Cell(10,10,$data->barang_kategori,1,0,'C');
            			$this->Cell(20,10,$data->material_type,1,0,'C');
            			$this->Cell(20,10,$data->nama_project,1,0,'C');
            			$this->Cell(30,10,$data->keterangan,1,0,'C');
            			$this->Ln();
                       
                    }
            	}
            }
            $pdf = new myPDF();
            $pdf->SetAutoPageBreak(true,70);
            $pdf->AliasNbPages();
            $pdf->AddPage('L','A4',0);
            $pdf->viewTable($db);
            $pdf->Output();;

            【讨论】:

            • 需要帮助包装 pdf
            【解决方案8】:

            你应该在单词之间使用空格,如果它不是空格字符串,它将保持原样......试试下面的

            <?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();
            ?>
            

            享受:)

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2020-03-19
              • 1970-01-01
              • 1970-01-01
              • 2016-05-14
              • 2013-04-15
              • 1970-01-01
              • 2014-05-03
              • 1970-01-01
              相关资源
              最近更新 更多