How to Create a Table with Image in PDF – C#

One month ago, I introduced a method to create a data table in PDF document. The table I create in that post is a simple table with data information. Today, I will show another method to create table with images by using C# in PDF.

Besides text and numbers, image will be taken as data information and inserted in cells sometimes. In my example, I save several countries information in database and one of items is about flag, which should be shown as image after I export it to PDF. However, at the beginning, flag information is saves as binary data in database.

The following steps show details. Because I use a .NET PDF component, Spire.PDF in my method, so I add its dll file as reference in project before starting with steps.

Steps

  1. Create a new PDF document. Then, set margin and add page.
  2. Add page title and set format.
  3. Set table format. There are two format styles, header styles and styles for data.
  4. Connect to database and get necessary information. At first, data is saved in DataTable, after drawing table in PDF, get information from DataTable.
  5. Set column width to make appearance be more wonderful.
  6. Set table layout. In this step, we can find that there are two methods table_BeingRowLayout and table_EndCellLayout used at first. Actually, the flag is also shown as binary data at present. Use table_BeginRowLayout method to convert data to image and set image height. Then, insert image to related column. Use table_EndCellLayout to move the flag information column to the second column. Secondly, set other table layout styles, including break, layout and end column. Thirdly, apply layout to table.
  7. Save and launch file.

Main Coding

using System;
using System.Drawing;
using System.IO;
using System.Data;
using System.Data.OleDb;
using Spire.Pdf;
using Spire.Pdf.Graphics;
using Spire.Pdf.Tables;

namespace TablewithImage
{
    class imagetable
    {
        static void Main(string[] args)
        {
            //Create
            PdfDocument doc = new PdfDocument();

            //Margin
            PdfUnitConvertor unitCvtr = new PdfUnitConvertor();
            PdfMargins margin = new PdfMargins();
            margin.Top = unitCvtr.ConvertUnits(2.54f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
            margin.Bottom = margin.Top;
            margin.Left = unitCvtr.ConvertUnits(3.17f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
            margin.Right = margin.Left;

            //Add Page
            PdfPageBase page = doc.Pages.Add(PdfPageSize.A4, margin);
            float y = 15;

            //Page Title
            PdfBrush brush1 = PdfBrushes.DarkCyan;
            PdfTrueTypeFont font1 = new PdfTrueTypeFont(new Font(“Calibri”, 14f, FontStyle.Regular));
            PdfStringFormat format1 = new PdfStringFormat(PdfTextAlignment.Center);
            page.Canvas.DrawString(“Country Information”, font1, brush1, page.Canvas.ClientSize.Width / 2, y, format1);
            y = y + font1.MeasureString(“Country Information”, format1).Height;
            y = y + 5;

            //Table Format
            PdfTable table = new PdfTable();
            table.Style.CellPadding = 2;
            table.Style.BorderPen = new PdfPen(brush1, 0.25f);
            table.Style.DefaultStyle.BackgroundBrush = PdfBrushes.AliceBlue;
            table.Style.DefaultStyle.Font = new PdfTrueTypeFont(new Font(“Calibri”, 11f));
            table.Style.DefaultStyle.TextBrush = PdfBrushes.SeaGreen;
            table.Style.HeaderSource = PdfHeaderSource.ColumnCaptions;
            table.Style.HeaderStyle.BackgroundBrush = PdfBrushes.LimeGreen;
            table.Style.HeaderStyle.Font = new PdfTrueTypeFont(new Font(“Calibri”, 12f, FontStyle.Bold));
            table.Style.HeaderStyle.TextBrush = PdfBrushes.WhiteSmoke;
            table.Style.HeaderStyle.StringFormat = new PdfStringFormat(PdfTextAlignment.Center);
            table.Style.ShowHeader = true;

            //Connect DataBase
            using (OleDbConnection conn = new OleDbConnection())
            {
                conn.ConnectionString = @”Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\work\My Documents\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))
                {
                    DataTable dataTable = new DataTable();
                    dataAdapter.Fill(dataTable);
                    dataTable.Columns.Add(new DataColumn(“FlagImage”, typeof(PdfImage)));
                    table.DataSourceType = PdfTableDataSourceType.TableDirect;
                    table.DataSource = dataTable;
                }
            }

            //Column Width
            float width
                = page.Canvas.ClientSize.Width
                    – (table.Columns.Count + 1) * table.Style.BorderPen.Width;
            table.Columns[0].Width = width * 0.20f;
            table.Columns[0].StringFormat
                = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);
            table.Columns[1].Width = width * 0.10f;
            table.Columns[1].StringFormat
                = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);
            table.Columns[2].Width = width * 0.19f;
            table.Columns[2].StringFormat
                = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);
            table.Columns[3].Width = width * 0.21f;
            table.Columns[3].StringFormat
                = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);
            table.Columns[4].Width = width * 0.12f;
            table.Columns[4].StringFormat
                = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);
            table.Columns[5].Width = width * 0.17f;
            table.Columns[5].StringFormat
                = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);

            //Table Layout
            table.BeginRowLayout += new BeginRowLayoutEventHandler(table_BeginRowLayout);
            table.EndCellLayout += new EndCellLayoutEventHandler(table_EndCellLayout);
            PdfTableLayoutFormat tableLayout = new PdfTableLayoutFormat();
            tableLayout.Break = PdfLayoutBreakType.FitElement;
            tableLayout.Layout = PdfLayoutType.Paginate;
            tableLayout.EndColumnIndex = table.Columns.Count – 2 – 1;
            PdfLayoutResult result = table.Draw(page, new PointF(0, y), tableLayout);
            y = y + result.Bounds.Height + 5;

            //Save
            doc.SaveToFile(“ImageTable.pdf”);
            doc.Close();

            //Launch
            System.Diagnostics.Process.Start(“ImageTable.pdf”);
        }

        static void table_EndCellLayout(object sender, EndCellLayoutEventArgs args)
        {
            if (args.RowIndex < 0)
            {
                //header
                return;
            }

            if (args.CellIndex == 1)
            {
                DataTable dataTable = (sender as PdfTable).DataSource as DataTable;
                PdfImage image = dataTable.Rows[args.RowIndex][7] as PdfImage;
                float x = (args.Bounds.Width – image.PhysicalDimension.Width) / 2 + args.Bounds.X;
                float y = (args.Bounds.Height – image.PhysicalDimension.Height) / 2 + args.Bounds.Y;
                args.Graphics.DrawImage(image, x, y);
            }
        }

        static void table_BeginRowLayout(object sender, BeginRowLayoutEventArgs args)
        {
            if (args.RowIndex < 0)
            {

                //header
                return;
            }

            DataTable dataTable = (sender as PdfTable).DataSource as DataTable;
            byte[] imageData = dataTable.Rows[args.RowIndex][6] as byte[];

            using (MemoryStream stream = new MemoryStream(imageData))
            {
                PdfImage image = PdfImage.FromStream(stream);
                args.MinimalHeight = 4 + image.PhysicalDimension.Height;
                dataTable.Rows[args.RowIndex][7] = image;
            }
        }
    }
}

Result Shown by Following:

Download Spire.PDF for .NET Here

Advertisements

Author: janewdaisy

.NET Program Beginner. Share methods about how to use C#/VB.NET to export data, operate Word, Excel, PDF and other useful skills.

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