2012-02-23 330 views
7

我希望能夠使用iTextSharp 4.2.0將圖像大小調整爲159x159的尺寸,但生成的圖像需要準確指定尺寸。iTextSharp:如何調整圖像大小以適應修正大小?

我已經試過這樣:

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

但圖像不是正方形。它保持縱橫比。

例子: 我有這樣的形象:

enter image description here

和結果圖像看起來應該魔神此:

enter image description here

感謝。

回答

29

您所描述的問題通常是當你試圖直接通過調用AddCell(),這總是縮放以適應PdfPCell圖像添加ImagePdfPTable會發生什麼。所以,如果您要添加的圖像到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); 
+0

這是一個非常有用的答案。謝謝。 – Emanuel 2012-02-23 15:14:43

+0

認真有用..謝謝。 – 2014-05-12 12:34:13

+1

還要小心不要通過'new PdfPCell().setImage(img)'添加圖像,這會添加圖像作爲單元格的背景,它會自動縮放以適合單元格的寬度和高度。 – 2014-07-04 08:36:24

0

PdfPCell擁有財產,以適應在細胞圖像,只需將它設置爲true。

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

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