Drawing Tables

This example demonstrates how to draw tables.

A table is an arrangement of data in rows and columns. Tables are widely used in communication, research, and data analysis

Clicking on the generate button will generate a pdf with several table formats /p>

  • cell with borders
  • cell with gradient colors
  • Row with colspan
  • Cell with image
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Text;
using OfficeComponent.Pdf;
using OfficeComponent.Pdf.Graphics;
using OfficeComponent.Pdf.Tables;

namespace OfficeComponent.Samples
{
    class DrawingTablesExample : ExampleBase
    {
        public DrawingTablesExample(string commonDataPath, string outputDir)
            : base(commonDataPath, outputDir)
        {
        }

        public DrawingTablesExample(string commonDataPath, string outputDir, string xmlFile) : base(commonDataPath, outputDir, xmlFile)
        {
        }

        private static string[,] CreateDataSource(int width, int height)
        {
            string[,] array = new string[height, width];

            for (int i = 0; i < height; i++)
            {
                float value = i;

                for (int j = 0; j < width; j++)
                {
                    float v = value + j * 0.5f;
                    array[i, j] = v.ToString();
                }
            }

            return array;
        }


        public override string Execute()
        {
            // Create a new instance of PdfDocument class.
            PdfDocument doc = new PdfDocument();

            //Set the font
            PdfPage page = doc.Pages.Add();

            const int w = 5;
            const int h = 5;
            int y = 10;

            string[,] array = CreateDataSource(w, h);

            PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 12);

            #region Gradient Table Sample

            page.Graphics.DrawString("Gradient Table Sample", font, PdfBrushes.Black, new PointF(200, y));

            PointF point2 = page.GetClientSize().ToPointF();
            point2.Y = 0;

            PdfCellStyle altStyle = new PdfCellStyle(font, PdfBrushes.White, PdfPens.Green);
            PdfLinearGradientBrush grBrush = new PdfLinearGradientBrush(PointF.Empty, point2, Color.FromArgb(0x25, 0x53, 0xff), Color.White);
            altStyle.BackgroundBrush = grBrush;

            PdfSimpleTable table = new PdfSimpleTable();
            table.DataSource = array;
            table.Style.AlternateStyle = altStyle;
            table.Style.BorderOverlapStyle = PdfBorderOverlapStyle.Inside;

            table.Style.CellSpacing = 2;
            table.Style.CellPadding = 4;
            table.Style.BorderPen = PdfPens.DarkGray;

            table.Draw(page, new PointF(0, y + 20));

            #endregion

            y += h * 30;

            #region Merging Cell

            array = CreateDataSource(w, h);

            page.Graphics.DrawString("Merging Cell Sample", font, PdfBrushes.Black, new PointF(200, y));

            table = new PdfSimpleTable();
            table.DataSource = array;
            altStyle = new PdfCellStyle(font, PdfBrushes.White, PdfPens.Black);
            altStyle.BackgroundBrush = PdfBrushes.LightBlue;
            table.Style.AlternateStyle = altStyle;
            table.Style.BorderOverlapStyle = PdfBorderOverlapStyle.Overlap;

            table.Style.CellSpacing = 0;
            table.Style.CellPadding = 3;
            table.Style.BorderPen = PdfPens.Black;

            table.BeforeRowLayout += table_MergeCellStartRowLayout;

            table.Draw(page, new PointF(0, y + 20));

            #endregion

            y += h * 28;

            #region Cell with Image

            array = CreateDataSource(w, h);

            page.Graphics.DrawString("Cell with Image", font, PdfBrushes.Black, new PointF(200, y));

            table = new PdfSimpleTable();
            table.DataSource = array;

            PdfColumnCollection columns = table.Columns;
            foreach (PdfColumn col in columns)
            {
                col.StringFormat = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);
            }

            altStyle = new PdfCellStyle(font, PdfBrushes.White, PdfPens.Black);
            altStyle.BackgroundBrush = new PdfSolidBrush(Color.FromArgb(0x31, 0x4e, 0xff));
            table.Style.AlternateStyle = altStyle;
            table.Style.BorderOverlapStyle = PdfBorderOverlapStyle.Overlap;

            table.Style.CellSpacing = 0;
            table.Style.CellPadding = 3;
            table.Style.BorderPen = PdfPens.Black;

            table.AfterCellLayout += table_CellWithImageAfterCellLayout;

            table.Draw(page, new PointF(0, y + 20));

            #endregion

            // Save and close the document.
            var outputPath = Path.Combine(OutputDir, this.GetType().Name + "_" + Guid.NewGuid().ToString() + ".pdf");
            doc.Save(outputPath);
            doc.Close(true);

            return outputPath;
        }
        static void table_CellWithImageAfterCellLayout(object sender, AfterCellLayoutEventArgs args)
        {
            PdfGraphics g = args.Graphics;

            if (args.RowIndex == 2 && args.CellIndex == 3)
            {
                g.DrawRectangle(PdfPens.Red, args.Bounds);
            }
            else if (args.RowIndex == 4 && args.CellIndex == 2)
            {
                RectangleF bounds = args.Bounds;
                PointF point1 = bounds.Location;
                PointF point2 = new PointF(bounds.Right, bounds.Bottom);

                g.DrawLine(PdfPens.Black, point1, point2);
            }
        }

        static void table_MergeCellStartRowLayout(object sender, BeforeRowLayoutEventArgs args)
        {
            int rowIndex = args.RowIndex;

            if (rowIndex == 2)
            {
                PdfFont font = new PdfStandardFont(PdfFontFamily.TimesRoman, 24, PdfFontStyle.Bold);
                PdfCellStyle cs = new PdfCellStyle(font, PdfBrushes.DarkBlue, PdfPens.Green);

                PointF point1 = PointF.Empty;
                PointF point2 = new PointF(300, 0);

                PdfLinearGradientBrush grBrush =
                    new PdfLinearGradientBrush(point1, point2, Color.DarkGray, Color.WhiteSmoke);

                grBrush.Extend = PdfExtend.Both;

                cs.BackgroundBrush = grBrush;

                args.CellStyle = cs;

                PdfSimpleTable table = (PdfSimpleTable)sender;
                int count = table.Columns.Count;

                int[] spanMap = new int[count];

                // Set just spanned cells. Other values are not important
                // except negatives that are not allowed.
                spanMap[0] = 2;
                spanMap[2] = 3;

                args.ColumnSpanMap = spanMap;

                //Sets row height.
                args.MinimalHeight = 30f;
            }
        }

    }
}
Imports System.IO
Imports System.Text
Imports OfficeComponent.Pdf
Imports OfficeComponent.Pdf.Graphics
Imports OfficeComponent.Pdf.Tables

Namespace OfficeComponent.Samples
	Friend Class DrawingTablesExample
		Inherits ExampleBase
		Public Sub New(ByVal commonDataPath As String, ByVal outputDir As String)
			MyBase.New(commonDataPath, outputDir)
		End Sub

		Public Sub New(ByVal commonDataPath As String, ByVal outputDir As String, ByVal xmlFile As String)
			MyBase.New(commonDataPath, outputDir, xmlFile)
		End Sub

		Private Shared Function CreateDataSource(ByVal width As Integer, ByVal height As Integer) As String(,)
			Dim array(height - 1, width - 1) As String

			For i As Integer = 0 To height - 1
				Dim value As Single = i

				For j As Integer = 0 To width - 1
					Dim v As Single = value + j * 0.5F
					array(i, j) = v.ToString()
				Next j
			Next i

			Return array
		End Function


		Public Overrides Function Execute() As String
			' Create a new instance of PdfDocument class.
			Dim doc As New PdfDocument()

			'Set the font
			Dim page As PdfPage = doc.Pages.Add()

			Const w As Integer = 5
			Const h As Integer = 5
			Dim y As Integer = 10

			Dim array(,) As String = CreateDataSource(w, h)

			Dim font As PdfFont = New PdfStandardFont(PdfFontFamily.Helvetica, 12)

'			#Region "Gradient Table Sample"

			page.Graphics.DrawString("Gradient Table Sample", font, PdfBrushes.Black, New PointF(200, y))

			Dim point2 As PointF = page.GetClientSize().ToPointF()
			point2.Y = 0

			Dim altStyle As New PdfCellStyle(font, PdfBrushes.White, PdfPens.Green)
			Dim grBrush As New PdfLinearGradientBrush(PointF.Empty, point2, Color.FromArgb(&H25, &H53, &Hff), Color.White)
			altStyle.BackgroundBrush = grBrush

			Dim table As New PdfSimpleTable()
			table.DataSource = array
			table.Style.AlternateStyle = altStyle
			table.Style.BorderOverlapStyle = PdfBorderOverlapStyle.Inside

			table.Style.CellSpacing = 2
			table.Style.CellPadding = 4
			table.Style.BorderPen = PdfPens.DarkGray

			table.Draw(page, New PointF(0, y + 20))

'			#End Region

			y += h * 30

'			#Region "Merging Cell"

			array = CreateDataSource(w, h)

			page.Graphics.DrawString("Merging Cell Sample", font, PdfBrushes.Black, New PointF(200, y))

			table = New PdfSimpleTable()
			table.DataSource = array
			altStyle = New PdfCellStyle(font, PdfBrushes.White, PdfPens.Black)
			altStyle.BackgroundBrush = PdfBrushes.LightBlue
			table.Style.AlternateStyle = altStyle
			table.Style.BorderOverlapStyle = PdfBorderOverlapStyle.Overlap

			table.Style.CellSpacing = 0
			table.Style.CellPadding = 3
			table.Style.BorderPen = PdfPens.Black

			AddHandler table.BeforeRowLayout, AddressOf table_MergeCellStartRowLayout

			table.Draw(page, New PointF(0, y + 20))

'			#End Region

			y += h * 28

'			#Region "Cell with Image"

			array = CreateDataSource(w, h)

			page.Graphics.DrawString("Cell with Image", font, PdfBrushes.Black, New PointF(200, y))

			table = New PdfSimpleTable()
			table.DataSource = array

			Dim columns As PdfColumnCollection = table.Columns
			For Each col As PdfColumn In columns
				col.StringFormat = New PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle)
			Next col

			altStyle = New PdfCellStyle(font, PdfBrushes.White, PdfPens.Black)
			altStyle.BackgroundBrush = New PdfSolidBrush(Color.FromArgb(&H31, &H4e, &Hff))
			table.Style.AlternateStyle = altStyle
			table.Style.BorderOverlapStyle = PdfBorderOverlapStyle.Overlap

			table.Style.CellSpacing = 0
			table.Style.CellPadding = 3
			table.Style.BorderPen = PdfPens.Black

			AddHandler table.AfterCellLayout, AddressOf table_CellWithImageAfterCellLayout

			table.Draw(page, New PointF(0, y + 20))

'			#End Region

			' Save and close the document.
			Dim outputPath = Path.Combine(OutputDir, Me.GetType().Name & "_" & Guid.NewGuid().ToString() & ".pdf")
			doc.Save(outputPath)
			doc.Close(True)

			Return outputPath
		End Function
		Private Shared Sub table_CellWithImageAfterCellLayout(ByVal sender As Object, ByVal args As AfterCellLayoutEventArgs)
			Dim g As PdfGraphics = args.Graphics

			If args.RowIndex = 2 AndAlso args.CellIndex = 3 Then
				g.DrawRectangle(PdfPens.Red, args.Bounds)
			ElseIf args.RowIndex = 4 AndAlso args.CellIndex = 2 Then
				Dim bounds As RectangleF = args.Bounds
				Dim point1 As PointF = bounds.Location
				Dim point2 As New PointF(bounds.Right, bounds.Bottom)

				g.DrawLine(PdfPens.Black, point1, point2)
			End If
		End Sub

		Private Shared Sub table_MergeCellStartRowLayout(ByVal sender As Object, ByVal args As BeforeRowLayoutEventArgs)
			Dim rowIndex As Integer = args.RowIndex

			If rowIndex = 2 Then
				Dim font As PdfFont = New PdfStandardFont(PdfFontFamily.TimesRoman, 24, PdfFontStyle.Bold)
				Dim cs As New PdfCellStyle(font, PdfBrushes.DarkBlue, PdfPens.Green)

				Dim point1 As PointF = PointF.Empty
				Dim point2 As New PointF(300, 0)

				Dim grBrush As New PdfLinearGradientBrush(point1, point2, Color.DarkGray, Color.WhiteSmoke)

				grBrush.Extend = PdfExtend.Both

				cs.BackgroundBrush = grBrush

				args.CellStyle = cs

				Dim table As PdfSimpleTable = CType(sender, PdfSimpleTable)
				Dim count As Integer = table.Columns.Count

				Dim spanMap(count - 1) As Integer

				' Set just spanned cells. Other values are not important
				' except negatives that are not allowed.
				spanMap(0) = 2
				spanMap(2) = 3

				args.ColumnSpanMap = spanMap

				'Sets row height.
				args.MinimalHeight = 30F
			End If
		End Sub

	End Class
End Namespace