Create Grids in PDF using Free API in C#

Introduction

A grid or a table is a great way to present data into groups. Manual generation of grids can appear as a boring task one could rather prefer to be automated. As a part of this article, I’ll dive into details of automatic grid creation and generation and show how to create perfect grids using a few small pieces of C# code and free .NET PDF component as the main tool.

The component used for generating grids is a simple and tiny class library that helps programmers to process PDF files on .NET platform. A grid in the library is represented by the PdfGrid class, helping to automate the creation of tabulated data in PDF. Its rows are represented by the PdfGridRow objects and cells by the PdfGirdCell objects. Each of them has a Style property that allows us to format the gird elements easily.

The following sections will demonstrate:

  • How to create a simple grid
  • How to merge cells, format text and cells in grid
  • How to dynamically create a grid using the data exported from database

Part 1. Simple grid with uniform cells

Let’s create the document containing a simple grid with uniform cells, using the code below.


//create a pdf object, add a page
PdfDocument doc = new PdfDocument();
PdfPageBase page = doc.Pages.Add();
//create a 2x4 gird object 
PdfGrid grid = new PdfGrid();
grid.Style.CellPadding = new PdfPaddings(1, 1, 1, 1);
PdfGridRow row1 = grid.Rows.Add();
PdfGridRow row2 = grid.Rows.Add();
grid.Columns.Add(4);
//set column width
foreach (PdfGridColumn col in grid.Columns)
{
    col.Width = 60f;
}
//insert data
for (int i = 0; i < grid.Columns.Count; i++)
{
    row1.Cells[i].Value = String.Format("col{0}", i+1);
    row2.Cells[i].Value = String.Format("{0}", i + 1);
}
//draw grid on pdf page
PdfLayoutResult result = grid.Draw(page, new PointF(10, 10));
//save document
doc.SaveToFile("Simple_Grid.pdf");

2017090401

Part 2. Grid with formatted cells, row spans and column spans

When creating a grid in a real PDF report, you may need to change the grid layout by merging certain cells or emphasize the important information by applying styles. The following code snippets will show you how to create an eye-catching and meaningful grid.


//create a pdf object, add a page
PdfDocument doc = new PdfDocument();
PdfPageBase page = doc.Pages.Add();
//create a 4x4 gird object 
PdfGrid grid = new PdfGrid();
grid.Style.CellPadding = new PdfPaddings(1, 1, 1, 1);
PdfGridRow row1 = grid.Rows.Add();
PdfGridRow row2 = grid.Rows.Add();
PdfGridRow row3 = grid.Rows.Add();
PdfGridRow row4 = grid.Rows.Add();
grid.Columns.Add(4);
//set column width
foreach (PdfGridColumn col in grid.Columns)
{
    col.Width = 60f;
}
//insert data
row1.Cells[0].Value = "Orders and Payments";
row2.Cells[0].Value = "Order";
row2.Cells[1].Value = "Date";
row2.Cells[2].Value = "Customer";
row2.Cells[3].Value = "Paid";
row3.Cells[0].Value = "00223";
row3.Cells[1].Value = "02/06/2016";
row3.Cells[2].Value = "JDX Co., Ltd";           
row3.Cells[3].Value = "Yes";
row4.Cells[0].Value = "00224";
row4.Cells[1].Value = "03/06/2016";
row4.Cells[3].Value = "No";
//horizontally and vertically merge certain cells through ColumnSpan and RowSpan
row1.Cells[0].ColumnSpan = 4;
row3.Cells[2].RowSpan = 2;
//align text
row1.Cells[0].StringFormat = new PdfStringFormat(PdfTextAlignment.Center);
row3.Cells[2].StringFormat = new PdfStringFormat(PdfTextAlignment.Justify, PdfVerticalAlignment.Middle);
//set background color of cells
row1.Cells[0].Style.BackgroundBrush = PdfBrushes.Gray;
row3.Cells[3].Style.BackgroundBrush = PdfBrushes.Green;
row4.Cells[3].Style.BackgroundBrush = PdfBrushes.MediumVioletRed;
//set font style
row1.Style.Font = new PdfTrueTypeFont(new Font("Arial", 9f, FontStyle.Bold));
row2.Style.Font = new PdfTrueTypeFont(new Font("Aril", 8f));
row3.Style.Font = new PdfTrueTypeFont(new Font("Aril", 8f));
row4.Style.Font = new PdfTrueTypeFont(new Font("Aril", 8f));
//format cells border
PdfBorders borders = new PdfBorders();
borders.All = new PdfPen(Color.Black, 0.1f);
foreach (PdfGridRow pgr in grid.Rows)
{
    foreach (PdfGridCell pgc in pgr.Cells)
    {
        pgc.Style.Borders = borders;
    }
}
//draw grid on pdf page
PdfLayoutResult result = grid.Draw(page, new PointF(10, 10));
//save document
doc.SaveToFile("Merge_Format_Cells.pdf");

2017090402

Part 3. Dynamically generate a grid from Access data

Often your application will pull data from a database and store it in the form of a DataTable. You may wish to easily insert this data into your document as a grid and quickly apply formatting to the whole grid. This part will demonstrate how to dynamically create a grid from Access data.

The MDB file looks as follows:
2017090403


//create a pdf document object, insert a page
PdfDocument doc = new PdfDocument();
PdfPageBase page = doc.Pages.Add();
//initialize a pdf grid
PdfGrid grid = new PdfGrid();
grid.Style.CellPadding = new PdfPaddings(2, 2, 2, 2);
//export data from database to grid
DataTable dataTable = new DataTable(); 
DataTable newTable = new DataTable();
using (OleDbConnection conn = new OleDbConnection())
{
    conn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=demo.mdb";
    OleDbCommand command = new OleDbCommand();
    command.CommandText
        = " select Name, '' as Flag, Capital, Continent, Area, Population, Flag as FlagData from country ";
    command.Connection = conn;
    using (OleDbDataAdapter dataAdapter = new OleDbDataAdapter(command))
    {
        dataAdapter.Fill(dataTable);
        dataAdapter.Fill(newTable);                 
        newTable.Columns.RemoveAt(newTable.Columns.Count - 1); 
        grid.DataSource = newTable;//export data from data table to grid
    }
}
//transfer binary flag data as images and insert them to grid cells
for (int i = 0; i < dataTable.Rows.Count; i++)
{
    PdfGridCellTextAndStyleList lst = new PdfGridCellTextAndStyleList();
    PdfGridCellTextAndStyle textAndStyle = new PdfGridCellTextAndStyle();
    byte[] imageData = dataTable.Rows[i][dataTable.Columns.Count - 1] as byte[];
    using (MemoryStream ms = new MemoryStream(imageData))
    {
        textAndStyle.Image = PdfImage.FromStream(ms);
        textAndStyle.ImageSize = new SizeF(10f, 10f);
        textAndStyle.ContentAlign = PdfGridCellContentAndAlign.Center;
        lst.List.Add(textAndStyle);
        grid.Rows[i].Cells[1].Value = lst;
        lst = null;
    }
}
//format header
grid.Headers[0].Style.BackgroundBrush = PdfBrushes.Gray;
grid.Headers[0].Style.Font= new PdfTrueTypeFont(new Font("Arial", 9f, FontStyle.Bold));
foreach (PdfGridCell cell in grid.Headers[0].Cells)
{
    cell.StringFormat = new PdfStringFormat(PdfTextAlignment.Center,PdfVerticalAlignment.Middle);     
    cell.Style.TextBrush = PdfBrushes.White;
}
//set column width
foreach (PdfGridColumn col in grid.Columns)
{
    col.Width = 80f;          
}         
//horizontally and vertically align text
for (int rowIndex = 0; rowIndex < grid.Rows.Count; rowIndex++)
{
    for (int i = 0; i < grid.Rows[rowIndex].Cells.Count; i++)
    {
        grid.Rows[rowIndex].Cells[i].StringFormat= new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);
    }
    //apply alternate style for odd and even rows
    if (rowIndex % 2 == 0)
    {
        grid.Rows[rowIndex].Style.BackgroundBrush = PdfBrushes.LightYellow;
    }
    else
        grid.Rows[rowIndex].Style.BackgroundBrush = PdfBrushes.LightBlue;
}
//draw grid on pdf page
PdfLayoutResult result = grid.Draw(page, new PointF(10, 10));
//save document
doc.SaveToFile("Generate_Grid_From_Database.pdf");

2017090404

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s