有时候我们需要批量的向一个文档中插入图片,比如说,我们使用OpexXML操作Word文件,或者使用ITextSharp操作PDF文件。
这里以ITextSharp操作PDF为例,现在有100张图片,插入到PDF中,每个图片占据一页。这里有个问题,因为这些图片的长度,像素等都是不确定的,我们怎么才能把图片摆在一个页面比较合适的位置上?我们可以考虑把图片放到页面的中间,也就是图片的对角线中心与页面的对角线中心重合。但是长度怎么办?有的图片长度可是完全超出了页面的宽带。所以,这时我们就要判断比较图片宽度与页面宽度,如果图片大,我们就缩小百分之九十,再比较,如果还大,继续缩小,直到图片宽度小于页面宽度为止。对于高度也是如此。
//获取图片对象实例
Image image = Image.GetInstance(path);
float percentage = 1;
//这里都是图片最原始的宽度与高度
float resizedWidht = image.Width;
float resizedHeight = image.Height;
//这时判断图片宽度是否大于页面宽度减去也边距,如果是,那么缩小,如果还大,继续缩小,
//这样这个缩小的百分比percentage会越来越小
while (resizedWidht > (doc.PageSize.Width - doc.LeftMargin - doc.RightMargin) * 0.8)
{
percentage = percentage * 0.9f;
resizedHeight = image.Height * percentage;
resizedWidht = image.Width * percentage;
}
//There is a 0.8 here. If the height of the image is too close to the page size height,
//the image will seem so big
while (resizedHeight > (doc.PageSize.Height - doc.TopMargin - doc.BottomMargin) * 0.8)
{
percentage = percentage * 0.9f;
resizedHeight = image.Height * percentage;
resizedWidht = image.Width * percentage;
}
//这里用计算出来的百分比来缩小图片
image.ScalePercent(percentage * 100);
//让图片的中心点与页面的中心店进行重合
image.SetAbsolutePosition(doc.PageSize.Width/2 - resizedWidht / 2, doc.PageSize.Height / 2 - resizedHeight / 2);
doc.Add(image);