2013-07-10 19 views
2

我一直在使用iTextSharp創建報表。我的報告有許多不同大小的圖像。儘管我對它們進行了縮放,但每幅圖像都呈現不同的大小。我發現很多解決方案,但沒有任何幫助無法爲圖像設置固定大小itextsharp

我的代碼:

PdfPCell InnerCell; 
iTextSharp.text.Image logo = iTextSharp.text.Image.GetInstance(Server.MapPath(@"images\Logo.png")); 
logo.ScaleToFit(80f, 80f); 
InnerCell.FixedHeight = 80f; 
InnerCell = new PdfPCell(logo); 

我嘗試添加圖像到塊,但圖像位置本身頂端。由於是一個動態報表,我不能指定x和y的值在塊

InnerCell = new PdfPCell(new Phrase(new Chunk(logo, 0, 0))); 

我甚至嘗試this但我不能得到一個固定的大小。

+0

如果使用ScaleToFit會發生什麼? –

+0

他們規模,但基於他們的原始大小。有些大和其他小不統一的高度和寬度 – Karthik

回答

6

ScaleToFit(w,h)將基於源圖像的寬度/高度的較大值成比例地縮放圖像。縮放多個圖像時,除非尺寸比例完全相同,否則將以不同的尺寸結束。這是設計。

使用ScaleToFit(80,80)

  • 如果源是一個正方形這100x100你會得到一個正方形這80x80
  • 如果源是一個矩形的200x100你會得到一個矩形的80x40
  • 如果你的來源是一個矩形,那麼你會得到一個矩形40x80

無論發生什麼,都要測量寬度和高度,並且至少有一個將是您指定的尺寸之一。

我創建的創建的隨機大小的圖像的示例程序並且它給我的圖片中顯示的期望的輸出(W = 80,H = 80,H = 80,H = 80,W = 80)

enter image description here

private void test() { 
    //Output the file to the desktop 
    var testFile = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Test.pdf"); 
    //Standard PDF creation here, nothing special 
    using (var fs = new FileStream(testFile, FileMode.Create, FileAccess.Write, FileShare.None)) { 
     using (var doc = new Document()) { 
      using (var writer = PdfWriter.GetInstance(doc, fs)) { 
       doc.Open(); 

       //Create a random number generator to create some random dimensions and colors 
       var r = new Random(); 

       //Placeholders for the loop 
       int w, h; 
       Color c; 
       iTextSharp.text.Image img; 

       //Create 5 images 
       for (var i = 0; i < 5; i++) { 
        //Create some random dimensions 
        w = r.Next(25, 500); 
        h = r.Next(25, 500); 
        //Create a random color 
        c = Color.FromArgb(r.Next(256), r.Next(256), r.Next(256)); 
        //Create a random image 
        img = iTextSharp.text.Image.GetInstance(createSampleImage(w, h, c)); 
        //Scale the image 
        img.ScaleToFit(80f, 80f); 
        //Add it to our document 
        doc.Add(img); 
       } 

       doc.Close(); 
      } 
     } 
    } 
} 

/// <summary> 
/// Create a single solid color image using the supplied dimensions and color 
/// </summary> 
private static Byte[] createSampleImage(int width, int height, System.Drawing.Color color) { 
    using (var bmp = new System.Drawing.Bitmap(width, height)) { 
     using (var g = Graphics.FromImage(bmp)) { 
      g.Clear(color); 
     } 
     using (var ms = new MemoryStream()) { 
      bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png); 
      return ms.ToArray(); 
     } 
    } 
} 

我認爲你在尋找什麼是按比例縮放圖像,但也有像「是尺寸」,這將意味着在明確或可能的白色像素的像素的其餘填充能力。請參閱this post以獲得解決方案。

+0

瞭解!令人敬畏的答案非常感謝.Got it working :) – Karthik

+0

對於所有圖像,我可以給所有圖像提供固定尺寸35x35嗎? –

+0

@ParthTrivedi,看到這個,如果這不起作用,那麼你需要打開一個新的問題。 http://stackoverflow.com/a/14598795/231316 –

相關問題