.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
abhays
Clintonzz
arronlee
mattyclown
cathyhill345

Home >> Articles >> ASP.NET >> Post New Resource Bookmark and Share   

 Subscribe to Articles

Create custom table in pdf document using ItextSharp

Posted By:Pankaj Mishra       Posted Date: January 06, 2010    Points: 25    Category: ASP.NET    URL: http://www.dotnetspark.com  
 

Create custom table in pdf document using ItextSharp

In this article we will see how to create table in pdf document using Itextsharp in asp.net. For some report which is in pdf format we need to add Table. You can build your own custom table using ItextSharp.
 
Itextsharp is an opensource free pdf generate libray which will generate the pdf and yes you can Create table and add into it.

you can also refer to my articles on ItextSharp in asp.net here to create table in pdf doc here

Step 1 : Download the ITextsharp library from here.

Step 2 : Add Itextsharp.dll to your project by rightlick and add reference on the propject explorer

Step 3 : Now add the Namespace to your .cs or .vb file

using iTextSharp.text;
using iTextSharp.text.pdf;

Step 4 :

Lets see this code which will be place Table into PDF document

  //Craete instance of the pdf table and set the number of column in that table

PdfPTable PdfTable = new PdfPTable(dt.Columns.Count);

PdfPCell PdfPCell = null; //Add Header of the pdf table PdfPCell = new PdfPCell(new Phrase(new Chunk("ID", font8))); PdfTable.AddCell(PdfPCell); PdfPCell = new PdfPCell(new Phrase(new Chunk("Name", font8))); PdfTable.AddCell(PdfPCell); //How add the data from datatable to pdf table for (int rows = 0; rows < dt.Rows.Count; rows++) { for (int column = 0; column < dt.Columns.Count; column++) { PdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Rows[rows][column].ToString(), font8))); PdfTable.AddCell(PdfPCell); } }

Now to see full code you can place the below code in any event like on button click

/// 
    /// Function which will create pdf document and save in the server folder
    /// 
    private void ExportDataToPDFTable()
    {
        Document doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35);
        try
        {

            string pdfFilePath = Server.MapPath(".") + "/pdf/myPdf.pdf";

            //Create Document class object and set its size to letter and give space left, right, Top, Bottom Margin
            PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream(pdfFilePath, FileMode.Create));

            doc.Open();//Open Document to write

             Font font8 = FontFactory.GetFont("ARIAL", 7);

            //Write some content
             Paragraph paragraph = new Paragraph("Using ITextsharp I am going to show how to create simple table in PDF document ");

            DataTable dt = GetDataTable();

            if (dt != null)
            {
                //Craete instance of the pdf table and set the number of column in that table
                PdfPTable PdfTable = new PdfPTable(dt.Columns.Count);
                PdfPCell PdfPCell = null;


                //Add Header of the pdf table
                PdfPCell = new PdfPCell(new Phrase(new Chunk("ID", font8)));
                PdfTable.AddCell(PdfPCell);

                PdfPCell = new PdfPCell(new Phrase(new Chunk("Name", font8)));
                PdfTable.AddCell(PdfPCell);


                //How add the data from datatable to pdf table
                for (int rows = 0; rows < dt.Rows.Count; rows++)
                {
                    for (int column = 0; column < dt.Columns.Count; column++)
                    {
                        PdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Rows[rows][column].ToString(), font8)));
                        PdfTable.AddCell(PdfPCell);
                    }
                }

                PdfTable.SpacingBefore = 15f; // Give some space after the text or it may overlap the table

                doc.Add(paragraph);// add paragraph to the document
                doc.Add(PdfTable); // add pdf table to the document

            }

        }
        catch (DocumentException docEx)
        {
            //handle pdf document exception if any
        }
        catch (IOException ioEx)
        {
            // handle IO exception
        }
        catch (Exception ex)
        {
            // ahndle other exception if occurs
        }
        finally
        {
            //Close document and writer
            doc.Close();

        }
    }

In Vb.Net sample function

 

''' 
''' Function which will create pdf document and save in the server folder
''' 
Private Sub ExportDataToPDFTable()
    Dim doc As New Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35)
    Try
        
        Dim pdfFilePath As String = Server.MapPath(".") & "/pdf/myPdf.pdf"
        
        'Create Document class object and set its size to letter and give space left, right, Top, Bottom Margin
        Dim wri As PdfWriter = PdfWriter.GetInstance(doc, New FileStream(pdfFilePath, FileMode.Create))
        
        doc.Open()
        'Open Document to write
        Dim font8 As Font = FontFactory.GetFont("ARIAL", 7)
        
        'Write some content
        Dim paragraph As New Paragraph("Using ITextsharp I am going to show how to create simple table in PDF document ")
        
        Dim dt As DataTable = GetDataTable()
        
        If dt IsNot Nothing Then
            'Craete instance of the pdf table and set the number of column in that table
            Dim PdfTable As New PdfPTable(dt.Columns.Count)
            Dim PdfPCell As PdfPCell = Nothing
            
            
            'Add Header of the pdf table
            PdfPCell = New PdfPCell(New Phrase(New Chunk("ID", font8)))
            PdfTable.AddCell(PdfPCell)
            
            PdfPCell = New PdfPCell(New Phrase(New Chunk("Name", font8)))
            PdfTable.AddCell(PdfPCell)
            
            
            'How add the data from datatable to pdf table
            For rows As Integer = 0 To dt.Rows.Count - 1
                For column As Integer = 0 To dt.Columns.Count - 1
                    PdfPCell = New PdfPCell(New Phrase(New Chunk(dt.Rows(rows)(column).ToString(), font8)))
                    PdfTable.AddCell(PdfPCell)
                Next
            Next
            
            PdfTable.SpacingBefore = 15F
            ' Give some space after the text or it may overlap the table
            doc.Add(paragraph)
            ' add paragraph to the document
                ' add pdf table to the document
            doc.Add(PdfTable)
            
        End If
    Catch docEx As DocumentException
        'handle pdf document exception if any
    Catch ioEx As IOException
        ' handle IO exception
    Catch ex As Exception
        ' ahndle other exception if occurs
    Finally
        'Close document and writer
            
        doc.Close()
    End Try
End Sub

In the above example I have create a sample datatable and using that datatable I have create table into pdf document. Below is the code of that datatable.

private DataTable GetDataTable()
    {
        // Create an object of DataTable class
        DataTable dataTable = new DataTable("MyDataTable");//Create ID DataColumn
        DataColumn dataColumn_ID = new DataColumn("ID", typeof(Int32));
        dataTable.Columns.Add(dataColumn_ID);//Create another DataColumn Name
        DataColumn dataColumn_Name = new DataColumn("Name", typeof(string));
        dataTable.Columns.Add(dataColumn_Name);
        //Now Add some row to newly created dataTable
        DataRow dataRow;for (int i = 0; i < 5; i++)
        {
            dataRow = dataTable.NewRow();
            // Important you have create New row
            dataRow["ID"] = i;dataRow["Name"] = "Some Text " + i.ToString();
            dataTable.Rows.Add(dataRow);
        }
        dataTable.AcceptChanges();
        return dataTable;
    }

Using the above method you can export any table like gridview, You can export gridview to pdf file. Just you need to assign the data souce as datatable

if you run the application after pasting the above code in your project you will see the sample pdf like this

Hope this will help all

Cheers!!!
Pankaj


 Subscribe to Articles

     

Further Readings:

Responses
Author: narama87         Company URL: http://www.dotnetspark.com
Posted Date: February 24, 2011

hello pankaj ,
thank you for this code but i think that GetDataTable()
for vb.net is missing , you gave as only GetDataTable()
for c#.net
Author: vishal anand         Company URL: http://www.dotnetspark.com
Posted Date: April 01, 2014

Respected Sir
Your article and your code is very good in creating custom table in pdf document using ItextSharp. But since i am using c# windows forms with sql server data and using ItextSharp. I get error in below line:

string pdfFilePath = Server.MapPath(".") + "/pdf/myPdf.pdf";

where i get Server does not exist in current record. I have added reference of ItextSharp in my document.

Tell me what reference or namespace should i include in c# windows forms(.Net Framework 4.5) with sql server 2008 using ItextSharp? Reply please I am waiting for your reply.
Author: Pankaj Mishra         Company URL: http://www.dotnetspark.com
Posted Date: April 02, 2014

Hi Vishal,

Server.MapPath() is for web application.

If you are using windows application than you can use full qualified path

eg

string pdfFilePath = = "C:\mydir\pdf\mypdf.pdf";

or you can use

string pdfFilePath = AppDomain.BaseDirectory + "\pdf\myPdf.pdf";

Note: code is not tested with visual studio but will be correct.
Author: vishal anand         Company URL: http://www.dotnetspark.com
Posted Date: April 02, 2014

Respected Pankaj Sir
Thank you for clarifying my doudt on such short notice. I am afraid i have to ask you my last question is that how do i fill columns with selected data from tables from sql server2008 into pdf report?

Given below is code for selecting selected datas from tables into columns from GetDataTable() the same you provided above just little modified:

public DataTable GetDataTable()
{

DataTable table = new DataTable("Techniciandetail" + "Technician");
DataColumn datacolumn_ID = new DataColumn("ID", typeof(Int32));
table.Columns.Add(datacolumn_ID);
DataColumn dataFname = new DataColumn("First Name", typeof(string));
table.Columns.Add(dataFname);
DataColumn dataMname = new DataColumn("Middle Name", typeof(string));
table.Columns.Add(dataMname);
DataColumn dataLname = new DataColumn("Last Name", typeof(string));
table.Columns.Add(dataLname);
DataColumn DOB = new DataColumn("DOB", typeof(DateTime));
table.Columns.Add(DOB);
DataColumn Sex = new DataColumn("Gender", typeof(string));
table.Columns.Add(Sex);
DataColumn Type = new DataColumn("Designation", typeof(Int32));
table.Columns.Add(Type);
DataRow drow = table.NewRow();
string connect = "Data Source=NPD-4\\SQLEXPRESS;Initial Catalog=DRRS;Integrated Security=true";
using (SqlConnection conn = new SqlConnection(connect))
{
string query = "Select t.technician_id,td.Technician_first_name,td.Technician_middle_name,td.Technician_last_name,t.technician_dob,t.technician_sex,td.technician_type from Techniciandetail td,Technician t where td.technician_id=t.technician_id and td.status=1";
SqlCommand cmd = new SqlCommand(query, conn);
try
{
conn.Open();
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
drow["ID"] = rdr[0].ToString();
drow["First Name"] = rdr[1].ToString();
drow["Middle Name"] = rdr[2].ToString();
drow["Last Name"] = rdr[3].ToString();
drow["DOB"] = rdr[4].ToString();
drow["Gender"] = rdr[5].ToString();
drow["Designation"] = rdr[6].ToString();
}
table.AcceptChanges();
return table;
}
}
catch (Exception ex)
{
throw ex;
}
}
}

The above GetDataTable() function does not work as when i call same function above like below:
DataTable dt = GetDataTable();
I only get column names in my pdf document.Tell me how to fill selected datas from sql query into appropriate columns in PDF report? Reply please Sir. I am waiting for your reply Sir.

Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend