FPDF align text LEFT, Center and Right

2019-04-29 16:15发布

问题:

I've have three cells and i'am trying to align the text to Left, Center and Right.

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


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

    $this->Cell(0,10,'Left text',0,0,'L');

    $this->Cell(0,10,'Center text:',0,0,'C');

    $this->Cell( 0, 10, 'Right text', 0, 0, 'R' ); 
} 

When I ouput my PDF file, center text get automatically aligned right. This is how it looks:

Can somebody tell me what I'm doing wrong here and how I can fix this issue?

回答1:

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


回答2:

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


标签: php pdf fpdf