2016-11-26 372 views
0

我想使用iTextSharp(v5.5.10)呈現圖像網格的PDF。圖像將具有相同的尺寸,並且應該均勻分佈在一頁上。設置iTextSharp中圖像網格之間的邊距或單元格間距PdfPTable

但是,使用下面提到的代碼,我很難設置合適的邊距或單元格之間的間距。

目測,這意味着預期的結果是這樣的:

expected

黃色突出顯示的行在哪裏我得到下面的結果,而不是問題:

actual

注意圖像之間沒有空格嗎?這是基於我的以下代碼:

public void CreateGridOfImages(string outputFilePath) 
    { 
     // note: these constants are in millimeters (mm), 
     // which are converted using the ToPoints() helper later on 
     const float spacingBetweenCells = 7; 
     const float imageWidth = 80; 
     const float imageHeight = 80; 
     const string[] images = new [] { "a.jpg", "b.jpg", "c.jpg" }; 

     using (var stream = new FileStream(outputFilePath, FileMode.CreateNew, FileAccess.Write, FileShare.None)) 
     { 
      var document = new iTextSharp.text.Document(PageSize.B2, 0f, 0f, 0f, 0f); 

      var writer = PdfWriter.GetInstance(document, stream); 

      try 
      { 
       document.Open(); 

       var table = new PdfPTable(5); 
       table.DefaultCell.Border = Rectangle.NO_BORDER; 

       foreach (var imagePath in images) 
       { 
        var img = iTextSharp.text.Image.GetInstance(imagePath); 
        img.ScaleToFit(ToPoints(imageWidth), ToPoints(imageHeight)); 

        var cell = new PdfPCell(); 

        // THIS IS THE PROBLEM... HOW TO SET IMAGE SPACING? 
        var cellMargin = ToPoints(spacingBetweenCells);      

        cell.AddElement(img); 

        table.AddCell(cell); 
       } 

       document.Add(table); 
      } 
      catch (Exception ex) 
      { 
       throw ex; 
      } 
      finally 
      { 
       document.Close(); 
      } 
     } 
    } 

    private float ToPoints(float millimeters) 
    { 
     // converts millimeters to points 
     return iTextSharp.text.Utilities.MillimetersToPoints(millimeters); 
    } 

現在這似乎微不足道。它problably是的,但我試過幾個選項,可能他們沒有正常工作(或全部):

  • 每個
  • 添加填充之間添加第()對象與墊襯到PdfPCell不似乎爲我工作
  • 看着定製IPdfPCellEvent樣品
  • 絕對定位影像產品總數(忘記PdfPTable)

我的直覺是,IPdfPCellEvent似乎正確的做法。但是所有的iText選項和變化都很簡單。

總結,沒有人知道我該如何正確設置邊距/單元格間距

回答

2

我假設你想擁有這個圖像中的第二個表:grid tables

在iText的表中創建單元格之間的白色空間的唯一途徑是向有關邊界設置爲背景色,並用該填充玩的細胞。我創建的細胞關鍵的代碼是:

  for(int i = 0; i < nrCols* nrRows;i++) { 
       var img = Image.GetInstance(imagePath); 
       img.ScaleToFit(ToPoints(imageWidth), ToPoints(imageHeight)); 
       //Create cell 
       var imageCell = new PdfPCell(); 
       imageCell.Image = img; 
       imageCell.Border = Rectangle.BOX; 
       imageCell.BorderColor = useColor? BaseColor.YELLOW : BaseColor.WHITE; 

       //Play with this value to change the spacing 
       imageCell.Padding = ToPoints(spacingBetweenCells/2); 

       imageCell.HorizontalAlignment = Element.ALIGN_CENTER; 

       grid.AddCell(imageCell); 
      } 

至於爲什麼添加填充到PdfPCell似乎沒有worrk:

爲什麼邊界仍然在你的例子中得出的原因,儘管

table.DefaultCell.Border = Rectangle.NO_BORDER; 

是因爲您從不使用默認單元格,因爲您使用var cell = new PdfPCell();創建了自定義單元格,並將自定義單元格傳遞給table.AddCell(cell);。如果你已經使用了table.addCell(img),邊框不會在那裏(雖然你的填充仍然不是你想要的間距,因爲它沒有設置在默認單元格上)。