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



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 :06/01/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

/// <summary>
    /// Function which will create pdf document and save in the server folder
    /// </summary>
    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

 

''' <summary>
''' Function which will create pdf document and save in the server folder
''' </summary>
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



Featured Articles


Best Practices No 5: - Detecting .NET application memory leaks
Memory leaks in .NET application have always being programmer's nightmare. Memory leaks are biggest problems when it comes to production servers. Productions servers normally need to run with least down time. Memory leaks grow slowly and after sometime they bring down the server by consuming huge chunks of memory. Maximum time people reboot the system, make it work temporarily and send a sorry note to the customer for the downtime. ... Read More
.NET Best Practice No: 1:- Detecting High Memory consuming functions in .NET code
One of the important factors for performance degradation in .NET code is memory consumption. Many developers just concentrate on execution time to determine performance bottle necks in a .NET application. Only measuring execution time does not clearly give idea of where the performance issue resides. Ok, said and done one of the biggest task is to understand which function, assembly or class has consumed how much memory. In this tutorial we will see how we can find which functions consume how much memory. This article discusses the best practices involved using CLR profiler for studying memory allocation.... Read More
How to improve your LINQ query performance by 5 X times ?
LINQ has been criticized by many early adopters for its performance issues. Well if you are just going to drag and drop using DBML code generator I am sure you will land up in to mess. Try doing this make a simple LINQ to SQL project using DBML and see your SQL profiler, I am sure you will never like to touch DBML code generator again. ... Read More
Responses

No response found. Be the first to respond this post

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