有時候我們需要批量的向一個文檔中插入圖檔,比如說,我們使用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);