Solved

export grid to pdf

Posted on 2014-03-17
18
364 Views
Last Modified: 2014-03-18
Hi experts
i am using obout grid, and i am trying to export grid to PDF, the export is working perfect when i fill the grid using sqldatasource but when i fill the grid using a stored procedure and function using code behind i am getting this error
error exporting
 i am attaching the code CustomerFeedbackByYear-v2.aspxCustomerFeedbackByYear-v2.aspx.cs

any suggestion
0
Comment
Question by:AZZA-KHAMEES
  • 9
  • 8
18 Comments
 
LVL 52

Expert Comment

by:Carl Tawn
ID: 39933910
You don't appear to be rebinding the grid before trying to export the data. The bindingsource will rebind for you but, since you are now populating the grid manually, you will need to rebind it yourself.

Try adding this line to the start of your ExportGridToPDF method:
// invoke method to rebind grid.
PopulateThGrid_Click(null, null)

Open in new window

If that works then you should also restructure the code so all of the binding stuff is done from a single method, rather than having to manually call a event handler.
0
 

Author Comment

by:AZZA-KHAMEES
ID: 39933913
thank you for the reply, i tried to do this but still the same problem
0
 
LVL 52

Expert Comment

by:Carl Tawn
ID: 39933915
Which line is throwing the exception?
0
 

Author Comment

by:AZZA-KHAMEES
ID: 39933919
i am getting error in
for (int i = 0; i < Grid1.Rows.Count; i++)
            {
                Hashtable dataItem = Grid1.Rows[i].ToHashtable();

                foreach (Column col in Grid1.Columns)
                {
                    
                        PdfPCell = new PdfPCell(new Phrase(new Chunk(dataItem[col.DataField].ToString(), font8)));
                        PdfPCell.RunDirection = PdfWriter.RUN_DIRECTION_LTR; //change the text direction for the arabic
                        PdfTable.AddCell(PdfPCell);
                   
                }
            }

Open in new window

i am getting error in the inner loop in
 PdfPCell = new PdfPCell(new Phrase(new Chunk(dataItem[col.DataField].ToString(), font8)));

Open in new window


the grid have 8 columns, and the inner loop read them all and when it reach the end it add another column lik it read 9 column instead of 8 then i got error in the line mentioned above, i tried to write Grid1.Columns-1 but it gave me error
0
 
LVL 52

Expert Comment

by:Carl Tawn
ID: 39933963
OK, so it doesn't sound like the issue is actually with the databinding, as you must have some data in your grid, otherwise it would have errored earlier.

When you run under the debugger what values do you get for Grid1.Rows.Count and Grid1.Columns.Count?
0
 
LVL 62

Expert Comment

by:Fernando Soto
ID: 39934128
Hi AZZA-KHAMEES;

I suspect that the exception is in this section of the line, dataItem[col.DataField].ToString(), I believe that one or more columns in the row has a null value in it. Run the application and when the exception is thrown copy and paste this, dataItem[col.DataField].ToString(), into the Watch window and see what its value is.
0
 

Author Comment

by:AZZA-KHAMEES
ID: 39936051
when i trace the code, the grid contain 8 columns but when i add watch it gave me 9 columns that why when the loop go through the data items it will be read correctly until it reach column 9 which is not available so the content will be null, i tried to add
foreach (Column col in Grid1.Columns - 1)
                {

Open in new window


but its wrong
0
 
LVL 52

Expert Comment

by:Carl Tawn
ID: 39936270
Try using:
foreach (Column col in Grid1.Columns - 1)
{
    if (col != null && dataItem.ContainsKey(col.DataField))
    {
          // rest of your code

Open in new window

That should test that the column is not null, and that the hashtable contains a corresponding value before it attempts to use it.
0
 

Author Comment

by:AZZA-KHAMEES
ID: 39936284
its working but another issues
it will write the first record correctly but when it move to the next record it will add the first column in the end of the first record which is wrong the second record suppose to be start in the second line
error
0
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 
LVL 52

Expert Comment

by:Carl Tawn
ID: 39936289
Can you post your code as it currently is? It sounds like something is screwy with the way your 3rd party control is working.
0
 

Author Comment

by:AZZA-KHAMEES
ID: 39936393
this is the full code for the function
private void ExportGridToPDF()
    {
        MappingVariable();
        DataTable dt = GetData(DirCode);
        Grid1.DataSource = dt;
        Grid1.DataBind();

        // Stream which will be used to render the data
        MemoryStream fileStream = new MemoryStream();
        
        Document doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35);
        try
        {            
            //Create Document class object and set its size to letter and give space left, right, Top, Bottom Margin
            PdfWriter wri = PdfWriter.GetInstance(doc, fileStream);

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

            //Font font8 = FontFactory.GetFont("TAHOMA", 7);
            BaseFont bf = BaseFont.CreateFont("c:\\\\windows\\\\fonts\\\\tahoma.ttf", BaseFont.IDENTITY_H, true);
            iTextSharp.text.Font font8 = new iTextSharp.text.Font(bf, 8, iTextSharp.text.Font.NORMAL);

            //Write some content
            Paragraph paragraph = new Paragraph("ASP.NET Grid - Export to PDF");

            //Craete instance of the pdf table and set the number of column in that table
            PdfPTable PdfTable = new PdfPTable(Grid1.Columns.Count);
            PdfPCell PdfPCell = null;
            
            //Add headers of the pdf table
            foreach (Column col in Grid1.Columns)
            {                
                PdfPCell = new PdfPCell(new Phrase(new Chunk(col.HeaderText, font8)));
                PdfPCell.RunDirection = PdfWriter.RUN_DIRECTION_LTR; //change the text direction for the arabic               
                PdfTable.AddCell(PdfPCell);
            }

            //How add the data from the Grid to pdf table
            for (int i = 0; i < Grid1.Rows.Count; i++)
            {
                Hashtable dataItem = Grid1.Rows[i].ToHashtable();

                foreach (Column col in Grid1.Columns)
                {
                    if (col != null && dataItem.ContainsKey(col.DataField))
                    {
                        PdfPCell = new PdfPCell(new Phrase(new Chunk(dataItem[col.DataField].ToString(), font8)));
                        PdfPCell.RunDirection = PdfWriter.RUN_DIRECTION_LTR; //change the text direction for the arabic
                        PdfTable.AddCell(PdfPCell);
                    }

                }
            }


           
            PdfTable.SpacingBefore = 15f;

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

        // Send the data and the appropriate headers to the browser
        Response.Clear();
        Response.AddHeader("content-disposition", "attachment;filename=oboutGrid.pdf");
        Response.ContentType = "application/pdf";
        Response.BinaryWrite(fileStream.ToArray());
        Response.End(); 
    }

Open in new window

0
 
LVL 52

Expert Comment

by:Carl Tawn
ID: 39936429
I think it's being thrown off by the fact that the section that is generating the headers has an extra column, which is then causing the rows to offset since you don't explicitly create a new row.

Try changing:
//Add headers of the pdf table
foreach (Column col in Grid1.Columns)
{                
    PdfPCell = new PdfPCell(new Phrase(new Chunk(col.HeaderText, font8)));
    PdfPCell.RunDirection = PdfWriter.RUN_DIRECTION_LTR; //change the text direction for the arabic               
    PdfTable.AddCell(PdfPCell);
}

Open in new window

To:
//Add headers of the pdf table
for (int i = 0; i < Grid1.Columns.Count - 1)
{                
    Column col = Grid1.Columns[i];
    PdfPCell = new PdfPCell(new Phrase(new Chunk(col.HeaderText, font8)));
    PdfPCell.RunDirection = PdfWriter.RUN_DIRECTION_LTR; //change the text direction for the arabic               
    PdfTable.AddCell(PdfPCell);
}

Open in new window

There is probably something about that extra column that you can use to identify that it isn't an actual data column, but I can't really offer any guidance on what it might be as I don't have your control library to play with.
0
 

Author Comment

by:AZZA-KHAMEES
ID: 39936538
i changed it but still the same problem
0
 
LVL 52

Expert Comment

by:Carl Tawn
ID: 39936540
Actually, change the -1 to a -2
0
 

Author Comment

by:AZZA-KHAMEES
ID: 39936590
changed it and still the same problem
it added the first column contents as column header in the end of the table
error
0
 
LVL 52

Accepted Solution

by:
Carl Tawn earned 500 total points
ID: 39936666
OK. Change it back to -1 and change this line:
PdfPTable PdfTable = new PdfPTable(Grid1.Columns.Count);

Open in new window

To:
PdfPTable PdfTable = new PdfPTable(Grid1.Columns.Count-1);

Open in new window

0
 

Author Comment

by:AZZA-KHAMEES
ID: 39936671
YESSSSS perfect finally, it worked :), thanks a lot for your help
0
 

Author Closing Comment

by:AZZA-KHAMEES
ID: 39936673
Thanks a lot :)
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, just open a new email message. In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
Learn how to create flexible layouts using relative units in CSS.  New relative units added in CSS3 include vw(viewports width), vh(viewports height), vmin(minimum of viewports height and width), and vmax (maximum of viewports height and width).

863 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now