Monday 24 August 2015

Export Datatable into PDF using asp.net c#


private void GeneratePDF(DataTable dataTable, string rptnm)
    {
        Document pdfDoc = new Document(PageSize.A2, 10f, 10f, 10f, 0f);
        System.IO.MemoryStream mStream = new System.IO.MemoryStream();
        PdfWriter writer = PdfWriter.GetInstance(pdfDoc, mStream);
        int cols = dataTable.Columns.Count;
        int rows = dataTable.Rows.Count;
        pdfDoc.Header = new HeaderFooter(new Phrase("Header Text”,false);
        pdfDoc.Open();
        iTextSharp.text.Table pdfTable = new iTextSharp.text.Table(cols, rows);
        pdfTable.BorderWidth = 1;pdfTable.Width = 100;
        pdfTable.Padding = 1;pdfTable.Spacing = 1;

        //creating table headers
        for (int i = 0; i < cols; i++)
        {
            Cell cellCols = new Cell();
            cellCols.BackgroundColor = new iTextSharp.text.Color(System.Drawing.ColorTranslator.FromHtml("#548B54"));
            iTextSharp.text.Font ColFont = FontFactory.GetFont(FontFactory.HELVETICA, 12, iTextSharp.text.Font.BOLD, iTextSharp.text.Color.WHITE);
            Chunk chunkCols = new Chunk(dataTable.Columns[i].ColumnName, ColFont);
            cellCols.Add(chunkCols);
            pdfTable.AddCell(cellCols);
        }
        //creating table data (actual result)

        for (int k = 0; k < rows; k++)
        {
            for (int j = 0; j < cols; j++)
            {
                Cell cellRows = new Cell();
                if (k % 2 == 0)
                {
                    cellRows.BackgroundColor = new iTextSharp.text.Color(System.Drawing.ColorTranslator.FromHtml("#cccccc")); ;
                }
                else { cellRows.BackgroundColor = new iTextSharp.text.Color(System.Drawing.ColorTranslator.FromHtml("#ffffff")); }
                iTextSharp.text.Font RowFont = FontFactory.GetFont(FontFactory.HELVETICA, 12);
                Chunk chunkRows = new Chunk(dataTable.Rows[k][j].ToString(), RowFont);
                cellRows.Add(chunkRows);

                pdfTable.AddCell(cellRows);
            }
        }
        pdfDoc.Add(pdfTable);
        pdfDoc.Close();
        Response.ContentType = "application/octet-stream";
        Response.AddHeader("Content-Disposition", "attachment; filename=Report.pdf");
        Response.Clear();
        Response.BinaryWrite(mStream.ToArray());
        Response.End();

    }

No comments:

Post a Comment

Excel Sort values in ascending order using function TEXTJOIN

 Excel ::  Text ::  1,3,5,2,9,5,11 Result :: 1,2,3,5,5,9,11 Formula ::     TEXTJOIN ( ",",1,SORT(MID(SUBSTITUTE( A1 ,","...