Display image in PDF using fpdf

2019-04-29 04:32发布

问题:

I want to insert an image in my created PDF file. However, it won't position well at all.

If I do this:

$fpdf->Image($row_products['prod_imagelarge'], 10); 

The images will appear however, they're too big.

If I do this:

$fpdf->Image($row_products['prod_imagelarge'],30, 40, 40, 40);

Not all images will appear. Only 1 image per page will appear but with the right size.

Actually, I am inserting an image inside a while loop. What I would want to display in the pdf file is: (in order)

-product name (works fine)  
-product image (the problem is here!)  
-product description (works fine)

回答1:

Similar to Naveed, but a little more complete with the rest of your row data. The trick is to capture the X and Y position before placing the image and then manually set the abscissa ("position") to the proper place, given the new image.

$image_height = 40;
$image_width = 40;
while ($row_products = mysql_fetch_array($products)) { 
   $fpdf->Cell(0, 0, $row_products['prod_name'], 0, 2);
   $fpdf->Cell(0, 0, $row_products['prod_description'], 0, 2);

   // get current X and Y
   $start_x = $fpdf->GetX();
   $start_y = $fpdf->GetY();

   // place image and move cursor to proper place. "+ 5" added for buffer
   $fpdf->Image($row_products['prod_imagelarge'], $fpdf->GetX(), $fpdf->GetY() + 5, 
                $image_height, $image_width) 
   $fpdf->SetXY($start_x, $start_y + $image_height + 5);
}


回答2:

If one page contains many images then may be your images are placed on each others. You should change position for each image on one page. Try something like this.

for( $i=10; $i<=200; $i=$i+10 ) {
  $fpdf->Image($row_products['prod_imagelarge'],30, $i, 40, 40);
}


标签: php image pdf fpdf