iTextSharp: How to resize an image to fit a fix si

2019-02-13 13:26发布

问题:

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:

And the result image should look loke this:

Thanks.

回答1:

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


回答2:

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