C# – iTextSharp: How to resize an image to fit a fix size


I want to be able to resize an image to the dimension of 159×159 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.

I have this image:

enter image description here

And the result image should look loke this:

enter image description here


Best Solution

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);

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

PdfPTable table = new PdfPTable(1);
table.AddCell(new PdfPCell(img));