2
votes

I am reading data from a database, and populating a table using iTextSharp. This is the way I'm reading the data:

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();

As you can see, I'm using 'foreach' to loop through the data and populate the table. That is the only way I know of populating the table (I'm fairly new to iTextSharp).

I have been trying to align the data to the middle of the cells. Also, I want to alternate the color of the rows (every other row). I have been trying things like this, inside the loop, with no results:

row[column].HorizontalAlignment = 1;

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

1

1 Answers

5
votes

Set the PdfPCell HorizontalAlignment and BackgroundColor properties.

Sample data:

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);

Create 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());
}

Output:

enter image description here