0
votes

I use to generate a PDF file from a gridview using iTextSharp.

I need a help because I am not familiar with iTextSharp.

I'm using two gridviews in my aspx page: gvProducts and gvUsers.

The generation a PDF file from a single (gvProducts) gridview using iTextSharp working correctly.

I can't print the first and second GridView in the same PDF.

This is what I want:

  1. Open PDF document;
  2. Print result of my first GridView;
  3. Print result of my second GridView;
  4. Close, Save and download PDF document in the client.

Anybody know how can I do that?

Thank you in advance.

My code below.

protected void ExportToPDFWithFormatting()
{
    //link button column is excluded from the list
    int colCount = gvProducts.Columns.Count - 1;

    //Create a table
    PdfPTable table = new PdfPTable(colCount);

    table.HorizontalAlignment = 1;
    table.WidthPercentage = 100;

    //create an array to store column widths
    int[] colWidths = new int[gvProducts.Columns.Count];

    PdfPCell cell;
    string cellText;

    //create the header row
    for (int colIndex = 0; colIndex < colCount; colIndex++)
    {

        table.SetWidths(new int[] { 0, 40, 120, 110, 60, 60, 100, 90, 100, 50, 50, 50, 40, 30, 260, 200, 0 });

        //fetch the header text
        cellText = Server.HtmlDecode(gvProducts.HeaderRow.Cells[colIndex].Text);

        //create a new cell with header text
        BaseFont bf = BaseFont.CreateFont(
                                BaseFont.HELVETICA,
                                BaseFont.CP1252,
                                BaseFont.EMBEDDED,
                                false);

        iTextSharp.text.Font font = new iTextSharp.text.Font(bf, 10, iTextSharp.text.Font.BOLD, BaseColor.WHITE);
        cell = new PdfPCell(new Phrase(cellText.Replace("<br />", Environment.NewLine), font));
        cell.HorizontalAlignment = Element.ALIGN_CENTER;
        cell.VerticalAlignment = Element.ALIGN_MIDDLE;
        cell.FixedHeight = 45f;

        //set the background color for the header cell
        cell.BackgroundColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#a52a2a"));

        //add the cell to the table. we dont need to create a row and add cells to the row
        //since we set the column count of the table to 4, it will automatically create row for
        //every 4 cells
        table.AddCell(cell);
    }


    //export rows from GridView to table
    for (int rowIndex = 0; rowIndex < gvProducts.Rows.Count; rowIndex++)
    {
        if (gvProducts.Rows[rowIndex].RowType == DataControlRowType.DataRow)
        {
            for (int j = 0; j < gvProducts.Columns.Count - 1; j++)
            {
                //fetch the column value of the current row
                cellText = Server.HtmlDecode(gvProducts.Rows[rowIndex].Cells[j].Text);

                //create a new cell with column value
                cell = new PdfPCell(new Phrase(cellText, FontFactory.GetFont("PrepareForExport", 8)));                   
                cell.HorizontalAlignment = Element.ALIGN_CENTER;
                cell.VerticalAlignment = Element.ALIGN_MIDDLE;
                cell.FixedHeight = 25f;

                //Set Color of Alternating row
                if (rowIndex % 2 != 0)
                {
                    cell.BackgroundColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#f5f5dc"));
                }
                else
                {
                    cell.BackgroundColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#fcfcfc"));
                }


                //add the cell to the table
                table.AddCell(cell);
            }
        }
    }

    //Create the PDF Document
    Document pdfDoc = new Document(PageSize.A3.Rotate(), 30f, 30f, 30f, 0f);

    PdfWriter.GetInstance(pdfDoc, Response.OutputStream);

    //open the stream
    pdfDoc.Open();
    table.HeaderRows = 1;
    iTextSharp.text.Font fdefault = FontFactory.GetFont("Verdana", 18, iTextSharp.text.Font.BOLD, BaseColor.BLUE);
    string s = "Report";
    pdfDoc.Add(new Paragraph(s, fdefault));

    //add the table to the document
    pdfDoc.Add(table);

    //close the document stream
    pdfDoc.Close();

    Response.ContentType = "application/pdf";
    Response.AddHeader("content-disposition", "attachment;" + DateTime.Now + ".pdf");
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.Write(pdfDoc);
    Response.End();
}

Edit #1

This is my code for generate pdf on GridView number two (gvUsers).

The code working but in the headers columns I have the names of GridView number one (gvProducts)... why?

    //start pdf gridview number two
    int colCountUsers = gvUsers.Columns.Count - 1;
    PdfPTable tableUsers = new PdfPTable(colCountUsers);
    tableUsers.HorizontalAlignment = 1;
    tableUsers.WidthPercentage = 100;
    int[] colWidthsUsers = new int[gvUsers.Columns.Count];
    PdfPCell cellUsers;
    string cellTextUsers;
    for (int colIndexUsers = 0; colIndexUsers < colCountUsers; colIndexUsers++)
    {
        tableUsers.SetWidths(new int[] { 0, 40, 120, 110, 60, 60, 100 });
        cellTextUsers = Server.HtmlDecode(gvProducts.HeaderRow.Cells[colIndexUsers].Text);
        BaseFont bfUsers = BaseFont.CreateFont(
                                BaseFont.HELVETICA,
                                BaseFont.CP1252,
                                BaseFont.EMBEDDED,
                                false);

        iTextSharp.text.Font fontUsers = new iTextSharp.text.Font(bfUsers, 10, iTextSharp.text.Font.BOLD, BaseColor.WHITE);
        cellUsers = new PdfPCell(new Phrase(cellTextUsers.Replace("<br />", Environment.NewLine), fontUsers));
        cellUsers.HorizontalAlignment = Element.ALIGN_CENTER;
        cellUsers.VerticalAlignment = Element.ALIGN_MIDDLE;
        cellUsers.FixedHeight = 45f;
        cellUsers.BackgroundColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#a52a2a"));
        tableUsers.AddCell(cellUsers);
    }


    for (int rowIndexUsers = 0; rowIndexUsers < gvUsers.Rows.Count; rowIndexUsers++)
    {
        if (gvUsers.Rows[rowIndexUsers].RowType == DataControlRowType.DataRow)
        {
            for (int j = 0; j < gvUsers.Columns.Count - 1; j++)
            {
                cellTextUsers = Server.HtmlDecode(gvUsers.Rows[rowIndexUsers].Cells[j].Text);
                cellUsers = new PdfPCell(new Phrase(cellTextUsers, FontFactory.GetFont("PrepareForExport", 8)));
                cellUsers.HorizontalAlignment = Element.ALIGN_CENTER;
                cellUsers.VerticalAlignment = Element.ALIGN_MIDDLE;
                cellUsers.FixedHeight = 25f;
                tableUsers.AddCell(cellUsers);
            }
        }
    }

    Document pdfDocUsers = new Document(PageSize.A3.Rotate(), 30f, 30f, 30f, 0f);
    PdfWriter.GetInstance(pdfDocUsers, Response.OutputStream);
    pdfDocUsers.Open();
    tableUsers.HeaderRows = 1;
    iTextSharp.text.Font fdefaultUsers = FontFactory.GetFont("Verdana", 18, iTextSharp.text.Font.BOLD, BaseColor.BLUE);
    string sUsers = "Users";
    pdfDocUsers.Add(new Paragraph(sUsers, fdefaultUsers));
    pdfDocUsers.Add(tableUsers);
    pdfDocUsers.Close();
    //end pdf gridview number two



    //in first pdf gridview
    //add the table to the document
    pdfDoc.Add(table);
    pdfDoc.Add(tableUsers);
1
Can you just create another PdfPTable tableUsers and do the similar manipulations with it and gvUsers, and then where you add first table to the pdf document pdfDoc.Add(table); also call pdfDoc.Add(tableUsers);. - myroman
I'm with @myroman, just do it twice. You say it doesn't work but you don't have the second block of code so we can't tell you why. I can tell you, however, to get rid of Response.Write(pdfDoc). That line of code doesn't do what you think it does. - Chris Haas
I'm confused, you've got two instance of the Document class, pdfDocUsers and pdfDoc, so you're making two separate and unrelated PDFs. Is that right and is that what you're intending? - Chris Haas
Not I need one only file pdf with the dates of two gridviews- - Antonio Mailtraq

1 Answers

0
votes
int colCount1 = gvProducts1.Columns.Count - 1;

//Create a table
PdfPTable table1 = new PdfPTable(colCount1);

table1.HorizontalAlignment = 1;
table1.WidthPercentage = 100;

//create an array to store column widths
int[] colWidths1 = new int[gvProducts1.Columns.Count];

PdfPCell cell1;
string cellText1;

//create the header row
for (int colIndex1 = 0; colIndex1 < colCount1; colIndex1++)
{

    table1.SetWidths(new int[] { 0, 40, 120, 110, 60, 60, 100, 90, 100, 50, 50, 50, 40, 30, 260, 200, 0 });

    //fetch the header text
    cellText1 = Server.HtmlDecode(gvProducts1.HeaderRow.Cells[colIndex1].Text);

    //create a new cell with header text
    BaseFont bf1 = BaseFont.CreateFont(
                            BaseFont.HELVETICA,
                            BaseFont.CP1252,
                            BaseFont.EMBEDDED,
                            false);

    iTextSharp.text.Font font1 = new iTextSharp.text.Font(bf, 10, iTextSharp.text.Font.BOLD, BaseColor.WHITE);
    cell1 = new PdfPCell(new Phrase(cellText.Replace("<br />", Environment.NewLine), font));
    cell1.HorizontalAlignment = Element.ALIGN_CENTER;
    cell1.VerticalAlignment = Element.ALIGN_MIDDLE;
    cell1.FixedHeight = 45f;

    //set the background color for the header cell
    cell1.BackgroundColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#a52a2a"));

    //add the cell to the table. we dont need to create a row and add cells to the row
    //since we set the column count of the table to 4, it will automatically create row for
    //every 4 cells
    table1.AddCell(cell1);
}


//export rows from GridView to table
for (int rowIndex1 = 0; rowIndex1 < gvProducts1.Rows.Count; rowIndex1++)
{
    if (gvProducts.Rows[rowIndex1].RowType == DataControlRowType.DataRow)
    {
        for (int j1 = 0; j1 < gvProducts1.Columns.Count - 1; j1++)
        {
            //fetch the column value of the current row
            cellText1 = Server.HtmlDecode(gvProducts1.Rows[rowIndex1].Cells[j].Text);

            //create a new cell with column value
            cell1 = new PdfPCell(new Phrase(cellText1, FontFactory.GetFont("PrepareForExport", 8)));                   
            cell1.HorizontalAlignment = Element.ALIGN_CENTER;
            cell1.VerticalAlignment = Element.ALIGN_MIDDLE;
            cell1.FixedHeight = 25f;

            //Set Color of Alternating row
            if (rowIndex1 % 2 != 0)
            {
                cell1.BackgroundColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#f5f5dc"));
            }
            else
            {
                cell1.BackgroundColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#fcfcfc"));
            }


            //add the cell to the table
            table1.AddCell(cell1);
        }
    }
}

//Create the PDF Document

//open the stream


//add the table to the document
pdfDoc.Add(table1);

//close the document stream
pdfDoc.Close();

Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;" + DateTime.Now + ".pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Write(pdfDoc);
Response.End();