user2516043
user2516043

Reputation: 159

Aligning image next to text in FPDF

Ok, I have an FPDF document I am writing in PHP, in this page i have a logo positioned perfect using set x and Y and that works fine.

What i want to do now is add an image next to a header, now again i can position this with x and y. The problem is the information in the page is dynamic and so setting the x and y will mean that the header may move but the image will not.

at the moment i have the image and cell set up like this below, but the header always sits one line below the image and i can not find away for them to sit on the same line.

 $pdf->Image('images/school.png');
 $pdf->Cell(10,10,"Education",0,1,'L');

Upvotes: 3

Views: 9462

Answers (1)

Simon Bengtsson
Simon Bengtsson

Reputation: 8151

Unfortunately FPDF doesn't know how to float text next to images. However, often workarounds exist. The method below writes a floating image. Note that you have to specify the height of the image. It should be pretty easy to rewrite it to also let you specify the width or nothing though.

class FloatPDF extends FPDF
{
    public function floatingImage($imgPath, $height) {
        list($w, $h) = getimagesize($imgPath);
        $ratio = $w / $h;
        $imgWidth = $height * $ratio;

        $this->Image($imgPath, $this->GetX(), $this->GetY());
        $this->x += $imgWidth;
    }
}

Here is a demo:

$pdf = new FloatPDF();

$imgPath = "/logo.png";
$pdf->SetFont(self::FONT, 'B', 20);
$height = 10;

$pdf->floatingImage($imgPath, $height);
$pdf->Write($height, " This is a text ");
$pdf->floatingImage($imgPath, $height);
$pdf->Write($height, " with floating images. ");
$pdf->floatingImage($imgPath, $height);

$pdf->Output('demo.pdf', 'D');

And here is what the demo looks like:

Floating images and text FPDF

Oh and by the way, you also sad you had problem with that the cell got printed on the next row after calling $pdf->Image(). One easy fix is to set the $y parameter in $pdf->Image() to $pdf->getY(). If the $y parameter is not set FPDF tries to be helpful and defaults to make a linebreak.

Upvotes: 8

Related Questions