简体   繁体   中英

fpdf + php how to insert an image in a cell on right side in pdf document?

$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.

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:

  • Get the image dimensions with getimagesize
  • Get the page dimensions in pixels with $pdf->w
  • Calculate the total page width and subtract the image width to get the left padding we need
  • Use $pdf->k to convert the left padding from pixels to user units
  • Print an empty boundary cell left of the image with $pdf->Cell
  • Print the image with $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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM