iTextSharp:如何调整图片大小以适应固定大小?

10

我希望使用iTextSharp 4.2.0将图像调整到159x159点的尺寸,但生成的图像需要恰好具有指定的尺寸。

我已经尝试过以下方法:

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

但是这个图像不是正方形。它保持纵横比。

例如: 我有这张图片:

enter image description here

结果图像应该看起来像这样:

enter image description here

谢谢。

2个回答

43

你所描述的问题通常是因为你尝试通过调用AddCell()直接将Image添加到PdfPTable中,这将始终缩放图像以适应PdfPCell。因此,如果你像这样将图像添加到Document

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

你的ScaleAbsolute()调用被忽略了。要获得你想要的缩放效果:

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

非常有用。谢谢。 - prem30488
1
同时请注意,不要使用“new PdfPCell().setImage(img)”添加图像,这将把图像添加为单元格的背景,它会自动按比例缩放以适应单元格的宽度和高度。 - Saorikido
1
设置fit属性对我有用:table.AddCell(new PdfPCell(img,true)); - Dan Mihai Patrascu

9

PdfPCell具有适应单元格中图片大小的属性,只需将其设置为true即可。

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

  PdfPCell logocell = new PdfPCell(logo,true); //  **PdfPCell(Image,Boolean Fit)**

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接