Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iTextSharp: How to resize an image to fit a fix size?

I want to be able to resize an image to the dimension of 159x159 points, using iTextSharp 4.2.0, but the resulting image need to have exactly the dimensions specified.

I've tried this:

Image image = Image.GetInstance(imagePath);
image.ScaleAbsolute(159f, 159f);

But the image is not a square. It keeps the aspect ratio.

Example: I have this image:

enter image description here

And the result image should look loke this:

enter image description here

Thanks.

like image 566
Emanuel Avatar asked Feb 23 '12 11:02

Emanuel


2 Answers

The problem you describe is typically what happens when you try and add an Image directly to a PdfPTable by calling AddCell(), which always scales the image to fit the PdfPCell. So if you're adding the image to the Document like this:

Image img = Image.GetInstance(imagePath);
img.ScaleAbsolute(159f, 159f);
PdfPTable table = new PdfPTable(1);
table.AddCell(img);
document.Add(table);

your ScaleAbsolute() call is ignored. To get the scaling you want:

PdfPTable table = new PdfPTable(1);
table.AddCell(new PdfPCell(img));
document.Add(table);
like image 61
kuujinbo Avatar answered Sep 20 '22 14:09

kuujinbo


PdfPCell has property to fit image in cell so just set it to true.

  iTextSharp.text.Image logo = iTextSharp.text.Image.GetInstance("/test.png");

  PdfPCell logocell = new PdfPCell(logo,true); //  **PdfPCell(Image,Boolean Fit)**
like image 30
Pragnesh Mistry Avatar answered Sep 19 '22 14:09

Pragnesh Mistry