Hide / Remove columns when exporting to PDF document using iTextSharp

I have a GridView with data. Some of the columns in my Gridview are hidden visible=false .

I am trying to export the GridView to a PDF document using iTextSharp but the columns that are set to visible=false are also showing in my PDF document and I don't want that.

How can I export my GridView data to a PDF document without the hidden columns?

This is what I've done so far:

protected void Button1_Click(object sender, EventArgs e)
{

    PdfPTable pdfTable = new PdfPTable(gvSchedule.HeaderRow.Cells.Count);
    foreach (GridViewRow gridViewRow in gvSchedule.Rows)
    {
        gvSchedule.Columns[0].Visible = false;
        gvSchedule.Columns[1].Visible = false;
        foreach (TableCell tableCell in gridViewRow.Cells)
        {
            gvSchedule.Columns[0].Visible = false;
            gvSchedule.Columns[1].Visible = false;

            PdfPCell pdfCell = new PdfPCell(new Phrase(tableCell.Text));
            pdfTable.AddCell(pdfCell);
        }
    }
    Document pdfDocument = new Document(PageSize.A4, 10f, 10f, 10f, 10f);
    PdfWriter.GetInstance(pdfDocument, Response.OutputStream);

    pdfDocument.Open();
    pdfDocument.Add(pdfTable);
    pdfDocument.Close();

    Response.ContentType = "application/pdf";
    Response.AppendHeader("content-disposition", "attachment;filename=mySchedule.pdf");
    Response.Write(pdfDocument);
    Response.Flush();
    Response.End();
}

The two columns that I DO NOT want to display on my PDF document are:

 <asp:BoundField DataField="Address" visible="false" HeaderText="Address" SortExpression="Address"/>

 <asp:BoundField DataField="Area" visible="false" HeaderText="Area" SortExpression="Area"/>

Upvotes: 1

Views: 1623

Answers (1)

Peru
Peru

Reputation: 2971

Am not familiar with iTextSharp

But looking at your code

//enter condition here to not add the row 
         foreach (TableCell tableCell in gridViewRow.Cells)
        {
            gvSchedule.Columns[0].Visible = false;
            gvSchedule.Columns[1].Visible = false;
          if(not visiblity false)
          {
            PdfPCell pdfCell = new PdfPCell(new Phrase(tableCell.Text));
            pdfTable.AddCell(pdfCell);
           } 
        }

That way based on visiblity you can avoid creating that column for all the rows

Hope this helps !

Upvotes: 1

Related Questions