使用iTextSharp设置单元格对齐和(备用)背景行颜色

时间:2017-03-14 00:39:32

标签: c# .net itext

我正在从数据库中读取数据,并使用iTextSharp填充表格。这就是我读数据的方式:

var db = Database.Open("NewDatabase");
var sql = 
    @"SELECT    FullName,
                [2017-01-02], [2017-01-03], [2017-01-04],
                ([2017-01-02] + [2017-01-03] + [2017-01-04]) as 'DatesSum',
                [Week1]
    FROM        [NewTable]";

var data = db.Query(sql);
var columns = data.First().Columns;                                                                          
var doc = new Document();                                                                                   
PdfWriter.GetInstance(doc, Response.OutputStream);                                                          
doc.Open();
PdfPTable table = new PdfPTable(new float[] {30f, 10f, 10f, 10f, 10f, 10f});

foreach(var row in data)                                                        
{
    foreach(var column in columns)
    {
        table.AddCell(new Phrase(row[column] != null ? row[column].ToString() : string.Empty));
    }
}

doc.Add(table);
doc.Close();

正如您所看到的,我正在使用'foreach'来遍历数据并填充表格。这是我知道填充表格的唯一方法(我对iTextSharp很新)。

我一直在尝试将数据对齐到单元格的中间位置。此外,我想交替行的颜色(每隔一行)。我一直在循环中尝试这样的事情,没有结果:

row[column].HorizontalAlignment = 1;

参考:https://www.mikesdotnetting.com/article/205/exporting-the-razor-webgrid-to-pdf-using-itextsharp

1 个答案:

答案 0 :(得分:3)

设置PdfPCell HorizontalAlignmentBackgroundColor属性。

示例数据:

static readonly int[,] data = new int[,] 
{ 
    { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 }
};
static readonly int rows = data.GetLength(0);
static readonly int columns = data.GetLength(1);

创建PDF:

var table = new PdfPTable(2) 
{ 
    HorizontalAlignment = Element.ALIGN_LEFT,
    WidthPercentage = 50 
};
var cell = new PdfPCell() {HorizontalAlignment = Element.ALIGN_CENTER};
using (var stream = new MemoryStream())
{
    using (var document = new Document())
    {
        PdfWriter.GetInstance(document, stream);
        document.Open();

        for (int i = 0; i < rows; ++i)
        {
            cell.BackgroundColor = i % 2 == 0
                ? BaseColor.LIGHT_GRAY : BaseColor.WHITE;
            for (int j = 0; j < columns; ++j)
            {
                cell.Phrase = new Phrase(data[i, j].ToString());
                table.AddCell(cell);
            }
        }
        document.Add(table);
    }
    File.WriteAllBytes(OUTPUT, stream.ToArray());
}

输出:

enter image description here