這是正確的,iTextSharp 不會自動調整太大的文件大小的圖像。所以它只是一個問題:
- 用左/右和頂部/底部頁邊距計算可用文檔的寬度和高度。
- 獲取圖像寬度和高度。
- 比較文檔的寬度和高度與圖像的寬度和高度。
- 如果需要,縮放圖像。
這裏有一種方法,請參閱在線評論:
// change this to any page size you want
Rectangle defaultPageSize = PageSize.A4;
using (Document document = new Document(defaultPageSize)) {
PdfWriter.GetInstance(document, STREAM);
document.Open();
// if you don't account for the left/right margins, the image will
// run off the current page
float width = defaultPageSize.Width
- document.RightMargin
- document.LeftMargin
;
float height = defaultPageSize.Height
- document.TopMargin
- document.BottomMargin
;
foreach (string path in imagePaths) {
Image image = Image.GetInstance(path);
float h = image.ScaledHeight;
float w = image.ScaledWidth;
float scalePercent;
// scale percentage is dependent on whether the image is
// 'portrait' or 'landscape'
if (h > w) {
// only scale image if it's height is __greater__ than
// the document's height, accounting for margins
if (h > height) {
scalePercent = height/h;
image.ScaleAbsolute(w * scalePercent, h * scalePercent);
}
}
else {
// same for image width
if (w > width) {
scalePercent = width/w;
image.ScaleAbsolute(w * scalePercent, h * scalePercent);
}
}
document.Add(image);
}
}
唯一值得注意的一點是,上述imagePaths
是string[]
,讓你可以測試添加圖片的集合,是大的時候會發生什麼以適應頁面。
另一種方法是把圖像中的一列,單細胞PdfPTable:
PdfPTable table = new PdfPTable(1);
table.WidthPercentage = 100;
foreach (string path in imagePaths) {
Image image = Image.GetInstance(path);
PdfPCell cell = new PdfPCell(image, true);
cell.Border = Rectangle.NO_BORDER;
table.AddCell(cell);
}
document.Add(table);
感謝完美的解決方案:) – kbvishnu 2014-08-23 13:16:42