Search code examples
phpfpdf

FPDF - PHP - Different styles on center cell


My problem is that I have a center text in a cell and I want the word "Client:" in bold and the rest in regular, like is centered I cant print "client:" first and after that print the name, neither use "write" function because is centered, please help.

    $pdf->SetTextColor(102, 106, 117);
    $pdf->SetFont('Arial', 'B', 15);
    $pdf->Cell(626,25,"Client: ".$name,0,0,'C',0);

Solution

  • We have to calculate position of centered text like follows:

    require("fpdf.php");
    
    $pdf = new FPDF();
    $pdf->AddPage();
    $pdf->SetTextColor(102, 106, 117);
    $fullCellWidth = $pdf->GetPageWidth();
    
    $pdf->SetFont("Arial", "", 15);
    $regularCell = "some name";
    $regularWidth = $pdf->GetStringWidth($regularCell);
    
    $pdf->SetFont("Arial", "B", 15);
    $boldCell = "Client: ";
    $boldWidth = $pdf->GetStringWidth($boldCell);
    
    $centerIndentX = ($fullCellWidth - $boldWidth - $regularWidth) / 2;
    
    $pdf->SetX($centerIndentX);
    $pdf->Cell($boldWidth, 25, $boldCell, 0, 0, "L");
    
    $pdf->SetX($centerIndentX + $boldWidth);
    $pdf->SetFont("Arial", "", 15);
    $pdf->Cell($regularWidth, 25, $regularCell, 0, 0, "L");
    
    $pdf->Output();
    

    The output PDF example - part of screenshot:

    enter image description here