FPDF align text LEFT, Center and Right

Seems that there is a parameter for this, so ('R' for right-aligning, 'C' for centering):

$pdf->Cell(0, 10, "Some text", 0, true, 'R');

will right align text. Also, notice that the first parameter ('width') is zero, so cell has 100% width.


Though Jan Slabon's answer was really good I still had issues with the center not being exactly centered on my page, maybe we have different versions of the library and that's what accounts for the slight differences, for instance he uses lMargin and on some versions that's not available. Anyway, the way it worked for me is this:

        $pdf = new tFPDF\PDF();
        //it helps out to add margin to the document first
        $pdf->setMargins(23, 44, 11.7);
        $pdf->AddPage();
        //this was a special font I used
        $pdf->AddFont('FuturaMed','','AIGFutura-Medium.ttf',true);
        $pdf->SetFont('FuturaMed','',16);

        $nombre = "NAME OF PERSON";
        $apellido = "LASTNAME OF PERSON";

        $pos = 10;
        //adding XY as well helped me, for some reaons without it again it wasn't entirely centered
        $pdf->SetXY(0, 10);

        //with SetX I use numbers instead of lMargin, and I also use half of the size I added as margin for the page when I did SetMargins
        $pdf->SetX(11.5);
        $pdf->Cell(0,$pos,$nombre,0,0,'C');

        $pdf->SetX(11.5);
        //$pdf->SetFont('FuturaMed','',12);
        $pos = $pos + 10;
        $pdf->Cell(0,$pos,$apellido,0,0,'C');
        $pdf->Output('example.pdf', 'F');

The new position after a Cell call will be set to the right of each cell if you set the ln-parameter of the Cell method to 0. You have to reset the x-coordinate before the last 2 Cell calls:

class Pdf extends FPDF {
    ...

    function Footer() 
    { 
        $this->SetY( -15 ); 

        $this->SetFont( 'Arial', '', 10 ); 

        $this->Cell(0,10,'Left text',0,0,'L');
        $this->SetX($this->lMargin);
        $this->Cell(0,10,'Center text:',0,0,'C');
        $this->SetX($this->lMargin);
        $this->Cell( 0, 10, 'Right text', 0, 0, 'R' ); 
    } 
}

Tags:

Php

Pdf

Fpdf