在 PHP 中用 Fpdf 换行文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23542244/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:47:46  来源:igfitidea点击:

Wrap Text in Fpdf in Php

phppdffpdfword-wrap

提问by Jay

I am trying to Wrap a text in the Cell using FPDF. here is my code.

我正在尝试使用 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();
?>

The output for this code looks like this enter image description here

此代码的输出如下所示 在此处输入图片说明

Now I want to Wrap that Xtra text which is there into the Cell. The xtra text should go into the second line. How should I do that.

现在我想将那里的 Xtra 文本包装到单元格中。xtra 文本应该进入第二行。我该怎么做。

when I use MultiCell for that line $pdf->MultiCell( 20, 7, 'Hi5(xtra)', 1); It is changing into the following.. enter image description here

当我为该行使用 MultiCell 时 $pdf->MultiCell( 20, 7, 'Hi5(xtra)', 1); 它正在变成以下.. 在此处输入图片说明

I have tried the Answer mentioned by Log1c It came out this way enter image description here

我已经尝试过 Log1c 提到的答案它是这样出来的 在此处输入图片说明

回答by Ravi Dhoriya ツ

Use MultiCell()instead Cell()

使用MultiCell()替代Cell()

Change this:

改变这个:

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

To:

到:

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

The MultiCell()is used for print text with multiple lines.

多单元()被用于与多行打印文本。

EDIT:

编辑:

I can see that MultiCell(), breaks the line so new cell will be placed below current position.

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

In such case you can calculate xand yco-ordinate and calculate new position and set position after outputting every cell.

在这种情况下,您可以在输出每个单元格后计算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();
?>

回答by Vigneswaran S

I dont think Multicell is the solution for this.Problems in using multicell.

我不认为 Multicell 是解决这个问题的方法。使用 multicell 的问题。

  • line breaks enter image description here
  • overlaps with next row enter image description here
  • More over we cant able predict how much height a cell may goes? eg: if first cell text length is 50 and the second text lenght is 100 then its height differs so we cant able to create as a table row.

    Even the above answer helps to solve only the break of line but not overlap problem.

  • 换行 在此处输入图片说明
  • 与下一行重叠 在此处输入图片说明
  • 更重要的是,我们无法预测一个单元格的高度是多少?例如:如果第一个单元格文本长度为 50,第二个文本长度为 100,则其高度不同,因此我们无法创建为表格行。

    即使上面的答案也有助于解决断线而不是重叠问题。

Here i came with a new solution for this.a new function vcell() uses only cell in it to make the expected output successfully.

在这里,我为此提供了一个新解决方案。一个新函数 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();
?>

enter image description here

在此处输入图片说明

Function explanation:

功能说明:

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);}
    } 

回答by Dave

i try this all solution but its break table row look. so i try this solution and its help me so much,

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

$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

参考:FPDF

回答by Chanaka Karunarathne

I have faced the same problem and try to find a way of whether is a cell enough or not for the text and divide height by amount of line and use result as for the particular cell height. But, it only make code very complex. then I switch to a library called html2pdf. It creates html table which no any above mentioned conflict, And that page convert to pdf file. Use html2pdf library.. it is the easiest way of creating pdf with automatically divided cell. you can download it hereand there are many guides in the internet.

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

回答by Rafael Muylaert

Try this: You can pass column widths, column alignments, fills and links as arrays. if width is a number, it will be the width of the whole table.

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

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

Should draw this:FPDF table

应该画这个:FPDF table

回答by Arie Ote

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

回答by Anri

you shoud use space between words, if it will be no space string it will remain as is ... try the following

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

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

enjoy :)

请享用 :)