C# tutorial: display images in cells of a table in PDF

Display images in cells of a table in PDF

In the previous page, you learnt to display data in a table and to format the table and its cells. In this tutorial, you will learn to display images in the cells of the table. For example, we are going to construct a table of the best gifts for women in Women's Day as shown below. The first column displays images. The second and third columns are product description, and price.

display in table

To get start, you need to have some images of gifts stored in the imggifts folder in the current working directory. You can download the sample images from the link at the end of this tutorial. Then create a table called tblgifst in SQL Server database. In my machine, this table is in the testdb database. The table has four columns: ID, FileName, Description, and Price. ID column stores uniqe id of the products. It is auto increment field. The FileStore column stores the file names of the images. The Description, and the Price columns store descriptions, and prices of the products

table in design

table in preview

Now, let's talk about C# code to display an image in a cell of a table in PDF page. To accomplish the task, you will use another version of the PdfPCell class that accepts an image object.

PdfPCell cell=new PdfPCell(Image img, bool fit);

To create an image object you can use the Jpeg class of iTextSharp. s

iTextSharp.text.Image img = new Jpeg(byte[] img);

The constructor of the Jpeg class takes an array of bytes of an image read from a file. You need to create a method to convert from an input image file to an array of bytes. Below is the imageToByteArray method that can be called to convert an image read from a file to an array of bytes.

//This method will be called to convert an image object to byte array
public static byte[] imageToByteArray(System.Drawing.Image imageori)
using (var ms = new MemoryStream())
  imageori.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
  return ms.ToArray();

To download the complete C# code and related files of this tutorial, please click here.


This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.