Reputation: 180
$image1 = "call.png";
$pdf->Cell(0,8,$pdf->Image($image1, $pdf->GetX()+2, $pdf->GetY()+2, 20.78),0,0,'',true);
I tried the above code to insert an image in a cell of pdf document. i want to align this image on right side in cell.
Upvotes: 0
Views: 19501
Reputation: 2010
In FPDF there are internal variables w
and h
for width and height, respectively. However, these are represented in the user units. By default, this is millimeters. Images are always going to be presented in pixels, which can cause a problem. That said, FPDF also tracks wPt
and hPt
, which give you the dimensions in a manner that can be very easily compared with to pixel units. Finally, there is k
, which is a scale unit that can be used to convert from the user units to pixels.
We will do the following:
getimagesize
$pdf->w
$pdf->k
to convert the left padding from pixels to user units$pdf->Cell
$pdf->Image
We will not put the image in a cell. Don't do this. Cells weren't built for images, only for strings. You will not get intended results if you attempt this method. Instead, opt for the method above. Code as such:
// Get image dimensions
$size = getimagesize('img.png');
if( $size===false )
die('Image does not exist.');
$wImg = $size[0];
$hImg = $size[1];
// Get PDF dimensions
$wPdf = $pdf->wPt;
$hPdf = $pdf->hPt;
// Calculate width necessary for the cell
$width = $wPdf - $wImg;
if( $width<0 )
{
error_log('Image is larger than page we\'re trying to print on.');
$width = 0;
}
// Convert pixel units to user units
$width /= $pdf->k;
$height /= $pdf->k;
// Print a boundary cell
$pdf->Cell($width,$height);
// Print image
$pdf->Image('img.png');
// Force a new line
$pdf->Ln();
I would recommend putting this into a function or something of the like if you plan to use it a lot. Note that this only works for right alignment. You will do a similar method with different calculations for center alignment. The boundaries to the left and right on the page are defined by FPDF and can be set in the constructor with SetMargins
Upvotes: 7