web-dev-qa-db-fra.com

Wrap Text en Fpdf en Php

J'essaye d'envelopper un texte dans la cellule en utilisant FPDF. voici mon code.

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

La sortie de ce code ressemble à ceci enter image description here

Maintenant, je veux envelopper ce texte Xtra qui est là dans la cellule. Le texte xtra devrait aller dans la deuxième ligne. Comment devrais-je faire ça.

lorsque j'utilise MultiCell pour cette ligne $ pdf-> MultiCell (20, 7, 'Hi5 (xtra)', 1); Il est en train de changer dans ce qui suit.enter image description here

J'ai essayé la réponse mentionnée par Log1c Elle est sortie de cette façon enter image description here

8
Jay

Utilisez MultiCell() à la place de Cell()

Change ça:

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

À:

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

Le MultiCell () est utilisé pour imprimer du texte avec plusieurs lignes.

EDIT:

Je peux voir que MultiCell() coupe la ligne afin que la nouvelle cellule soit placée au-dessous de la position actuelle.

Dans ce cas, vous pouvez calculer les coordonnées x et y et calculer la nouvelle position et définir la position après la sortie de chaque cellule.

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

Je ne pense pas que Multicell soit la solution pour cela. Problèmes d'utilisation de multicell.

  • sauts de ligne  enter image description here
  • chevauche la rangée suivante  enter image description here
  • De plus, nous ne pouvons pas prédire quelle hauteur une cellule peut atteindre? Exemple: si la longueur du texte de la première cellule est de 50 et la longueur du second texte de 100, sa hauteur est différente, nous ne pouvons donc pas créer une ligne de tableau.

    Même la réponse ci-dessus permet de résoudre uniquement le problème de rupture de ligne, mais non de chevauchement.

Ici, je suis arrivé avec une nouvelle solution pour cela. Une nouvelle fonction vcell () utilise uniquement une cellule pour rendre la sortie attendue avec succès.

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

Explication de la fonction:

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);}
    } 
3
Vigneswaran S

J'ai été confronté au même problème et j'essaie de déterminer si une cellule est suffisante ou non pour le texte et divise la hauteur par le nombre de lignes et le résultat obtenu en fonction de la hauteur de la cellule. Mais cela rend le code très complexe. je passe ensuite à une bibliothèque appelée html2pdf. Il crée une table html qui ne contient aucun conflit mentionné ci-dessus, et cette page est convertie en fichier pdf. Utilisez la bibliothèque html2pdf .. c’est le moyen le plus simple de créer un pdf avec une cellule divisée automatiquement. vous pouvez le télécharger ici et il existe de nombreux guides sur Internet.

0

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

0
Arie Ote

j'essaie toutes ces solutions, à l'exception de son look de rangée de table de repos. , alors j'essaie cette solution et cela m'aide beaucoup,

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

référence : FPDF

0
Dave

Essayez ceci: Vous pouvez définir la largeur, l’alignement, le remplissage et les liens des colonnes sous forme de tableaux. si width est un nombre, ce sera la largeur de la table entière.

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

Devrait dessiner ceci: Tableau FPDF

0
Rafael Muylaert