Click here to Skip to main content
15,888,113 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have a datagridview and I need to export only selected rows to pdf using itextsharp in C#. I am able to export datagridview's headers to pdf.

problem 1 - I need to get whole headers to one column in pdf
problem 2 - I need to appear selected row data in front of relevent colomns.

What I have tried:

C#
iTextSharp.text.Font text = new iTextSharp.text.Font(bf, 11, iTextSharp.text.Font.NORMAL);

        Document doc = new Document(PageSize.A2.Rotate(), 1, 1, 1, 1);
        PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream("Test.pdf", FileMode.Create));
        doc.Open();

        
        PdfPTable pdftable = new PdfPTable(dataGridView1.ColumnCount - 0);

        for (int j = 0; j < dataGridView1.Columns.Count - 0; j++)
        {
            PdfPCell cell = new PdfPCell(new Phrase(dataGridView1.Columns[j].HeaderText, text));
            cell.BackgroundColor = BaseColor.LIGHT_GRAY;
            pdftable.AddCell(cell);
        }

        pdftable.HeaderRows = 0;
        for (int i = 0; i < dataGridView1.SelectedRows.Count; i++)
        //for (int i = 0; i < dgvLoadAll.Rows.Count; i++)
        {
            for (int k = 0; k < dataGridView1.Columns.Count - 0; k++)
            {

                if (dataGridView1[k, i].Value != null)
                {
                    pdftable.AddCell(new Phrase(dataGridView1.SelectedRows[i].Cells[k].Value.ToString(), text));
                    //pdftable.AddCell(new Phrase(dgvLoadAll[k, i].Value.ToString(), text));

                }
            }
        }

        //float[] widths = new float[] { 15f, 50f, 40f, 40f, 40f, 40f, 40f, 40f, 40f, 40f, 40f, 40f, 40f, 40f, 40f, 40f, 40f };

        // pdftable.SetWidths(widths);
        doc.Add(pdftable);
        doc.Close(); 
        System.Diagnostics.Process.Start("Test.pdf");
    }
Posted
Updated 15-Feb-17 19:33pm
v2

1 solution

One thing I notice in your code that looks suspect is when you say
C#
if(dataGridView1[k, i].Value != null)

// I think it should be

if(dataGridView1[i,k].Value != null)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900