2016-11-26 378 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),边框不会在那里(虽然你的填充仍然不是你想要的间距,因为它没有设置在默认单元格上)。