Sunday, November 11, 2012

Export to Pdf using itextsharp

using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.html;

private void ExporttoPdf()
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                try
                {
                    Document document = new Document(PageSize.A4, 25f, 25f, 25f, 25f);
                    string Path = System.IO.Path.GetTempPath() + "Correspondence Report.pdf";
                    if (File.Exists(Path))
                        File.Delete(Path);
                    PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(Path, FileMode.Create));
                    document.Open();
                    PdfPTable pdfgridtable = new PdfPTable(5);
                    pdfgridtable.DefaultCell.FixedHeight = 25;
                    float[] gridwidths = new float[] { 20f, 20f, 20f, 20f, 20f };
                    pdfgridtable.SetWidths(gridwidths);
                    pdfgridtable.WidthPercentage = 100;
                    PdfPCell pdfgridcell1 = new PdfPCell(new Phrase("NAME", new Font(Font.HELVETICA, 7.5f, Font.BOLD, Color.BLACK)));
                    pdfgridcell1.HorizontalAlignment = Element.ALIGN_CENTER;
                    pdfgridcell1.PaddingTop = 1f;
                    pdfgridcell1.PaddingBottom = 4f;
                    pdfgridtable.AddCell(pdfgridcell1);
                    PdfPCell pdfgridcell2 = new PdfPCell(new Phrase("SUBJECT", new Font(Font.HELVETICA, 7.5f, Font.BOLD, Color.BLACK)));
                    pdfgridcell2.HorizontalAlignment = Element.ALIGN_CENTER;
                    pdfgridcell2.PaddingTop = 1f;
                    pdfgridcell2.PaddingBottom = 4f;
                    pdfgridtable.AddCell(pdfgridcell2);
                    PdfPCell pdfgridcell3 = new PdfPCell(new Phrase("SENDER NAME", new Font(Font.HELVETICA, 7.5f, Font.BOLD, Color.BLACK)));
                    pdfgridcell3.HorizontalAlignment = Element.ALIGN_CENTER;
                    pdfgridcell3.PaddingTop = 1f;
                    pdfgridcell3.PaddingBottom = 4f;
                    pdfgridtable.AddCell(pdfgridcell3);
                    PdfPCell pdfgridcell4 = new PdfPCell(new Phrase("RECEIVED DATE", new Font(Font.HELVETICA, 7.5f, Font.BOLD, Color.BLACK)));
                    pdfgridcell4.HorizontalAlignment = Element.ALIGN_CENTER;
                    pdfgridcell4.PaddingTop = 1f;
                    pdfgridcell4.PaddingBottom = 4f;
                    pdfgridtable.AddCell(pdfgridcell4);
                    PdfPCell pdfgridcell5 = new PdfPCell(new Phrase("SUBJECT CATEGORY", new Font(Font.HELVETICA, 7.5f, Font.BOLD, Color.BLACK)));
                    pdfgridcell5.HorizontalAlignment = Element.ALIGN_CENTER;
                    pdfgridcell5.PaddingTop = 1f;
                    pdfgridcell5.PaddingBottom = 4f;
                    pdfgridcell5.NoWrap = false;
                    pdfgridtable.AddCell(pdfgridcell5);
                    PdfPCell pdfgridcell11 = null;
                    PdfPCell pdfgridcell22 = null;
                    PdfPCell pdfgridcell33 = null;
                    PdfPCell pdfgridcell44 = null;
                    PdfPCell pdfgridcell55 = null;
                    foreach (GridViewRow gvrow in gvReportview.Rows)
                    {
                        for (int i = 0; i < gvrow.Cells.Count; i++)
                        {
                            string CellText = string.Empty;
                            if (i == 0)
                            {
                                Label lblreferenceno = (Label)gvrow.FindControl("lblreferenceno");
                                if (!string.IsNullOrEmpty(lblreferenceno.Text))
                                    CellText = lblreferenceno.Text;
                                else
                                {
                                    HyperLink lnkview = (HyperLink)gvrow.FindControl("lnkview");
                                    CellText = lnkview.Text;
                                }
                                if (String.IsNullOrEmpty(CellText))
                                    CellText = " ";
                                pdfgridcell11 = new PdfPCell(new Phrase(CellText.Replace("&nbsp;", " "), new Font(Font.HELVETICA, 7.5f, Font.NORMAL, Color.BLACK)));
                                pdfgridcell11.HorizontalAlignment = Element.ALIGN_LEFT;
                                pdfgridcell11.PaddingBottom = 6f;
                                pdfgridcell11.PaddingTop = 1f;
                                pdfgridcell11.Padding = 5f;
                                pdfgridtable.AddCell(pdfgridcell11);
                            }
                            else if (i == 1)
                            {
                                Label lblreferenceno = (Label)gvrow.FindControl("lbltitle");
                                if (!string.IsNullOrEmpty(lblreferenceno.Text))
                                    CellText = lblreferenceno.Text;
                                if (String.IsNullOrEmpty(CellText))
                                    CellText = " ";
                                pdfgridcell22 = new PdfPCell(new Phrase(CellText.Replace("&nbsp;", " "), new Font(Font.HELVETICA, 7.5f, Font.NORMAL, Color.BLACK)));
                                pdfgridcell22.HorizontalAlignment = Element.ALIGN_LEFT;
                                pdfgridcell22.PaddingBottom = 6f;
                                pdfgridcell22.PaddingTop = 1f;
                                pdfgridcell22.Padding = 5f;
                                pdfgridtable.AddCell(pdfgridcell22);
                            }
                            else if (i == 2)
                            {
                                Label lblreferenceno = (Label)gvrow.FindControl("lblsender");
                                if (!string.IsNullOrEmpty(lblreferenceno.Text))
                                    CellText = lblreferenceno.Text;
                                if (String.IsNullOrEmpty(CellText))
                                    CellText = " ";
                                pdfgridcell33 = new PdfPCell(new Phrase(CellText.Replace("&nbsp;", " "), new Font(Font.HELVETICA, 7.5f, Font.NORMAL, Color.BLACK)));
                                pdfgridcell33.HorizontalAlignment = Element.ALIGN_LEFT;
                                pdfgridcell33.PaddingBottom = 6f;
                                pdfgridcell33.PaddingTop = 1f;
                                pdfgridcell33.Padding = 5f;
                                pdfgridtable.AddCell(pdfgridcell33);
                            }
                            else if (i == 3)
                            {
                                Label lblreferenceno = (Label)gvrow.FindControl("lblreceiveddate");
                                if (!string.IsNullOrEmpty(lblreferenceno.Text))
                                    CellText = lblreferenceno.Text;
                                if (String.IsNullOrEmpty(CellText))
                                    CellText = " ";
                                pdfgridcell44 = new PdfPCell(new Phrase(CellText.Replace("&nbsp;", " "), new Font(Font.HELVETICA, 7.5f, Font.NORMAL, Color.BLACK)));
                                pdfgridcell44.HorizontalAlignment = Element.ALIGN_LEFT;
                                pdfgridcell44.PaddingBottom = 6f;
                                pdfgridcell44.PaddingTop = 1f;
                                pdfgridcell44.Padding = 5f;
                                pdfgridtable.AddCell(pdfgridcell44);
                            }
                            else if (i == 4)
                            {
                                Label lblreferenceno = (Label)gvrow.FindControl("lblsubject");
                                if (!string.IsNullOrEmpty(lblreferenceno.Text))
                                    CellText = lblreferenceno.Text;

                                if (String.IsNullOrEmpty(CellText))
                                    CellText = " ";
                                pdfgridcell55 = new PdfPCell(new Phrase(CellText.Replace("&nbsp;", " "), new Font(Font.HELVETICA, 7.5f, Font.NORMAL, Color.BLACK)));
                                pdfgridcell55.HorizontalAlignment = Element.ALIGN_LEFT;
                                pdfgridcell55.PaddingBottom = 6f;
                                pdfgridcell55.PaddingTop = 1f;
                                pdfgridcell55.Padding = 5f;
                                pdfgridtable.AddCell(pdfgridcell55);
                            }
                        }
                    }

                    document.Add(pdfgridtable);
                    document.Close();
                    ShowPdf(Path);
                }
                catch (Exception ex)
                {
                    lblMsg.ForeColor = System.Drawing.Color.Red;
                    lblMsg.Text = ex.Message.ToString();
                }
            });
        }

private void ShowPdf(string strS)
        {
            try
            {
                Response.ClearContent();
                Response.ClearHeaders();
                if (strS.Contains("xls"))
                    Response.ContentType = "application/xls";
                else if (strS.Contains("xls"))
                    Response.ContentType = "application/pdf";
                Response.AddHeader
                ("Content-Disposition", "attachment; filename=" + strS);
                //Response.TransmitFile(strS);
                //Response.End();
                Response.WriteFile(strS);
                Response.Flush();
                Response.Clear();
            }
            catch (Exception ex)
            {
                lblMsg.ForeColor = System.Drawing.Color.Red;
                lblMsg.Text = ex.Message.ToString();
            }
        }

Export to Excel by Interop Services

using System.Runtime.InteropServices;
using excel = Microsoft.Office.Interop.Excel;

private void ExporttoExcel()
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                try
                {
                    Microsoft.Office.Interop.Excel.Application oXL;
                    Microsoft.Office.Interop.Excel.Workbook oWB;
                    Microsoft.Office.Interop.Excel.Worksheet oSheet;
                    Microsoft.Office.Interop.Excel.Range oRange;

                    // Start Excel and get Application object.
                    oXL = new Microsoft.Office.Interop.Excel.Application();

                    // Set some properties
                    oXL.Visible = true;
                    oXL.DisplayAlerts = false;

                    // Get a new workbook.
                    oWB = oXL.Workbooks.Add(Missing.Value);
                    oSheet = (Microsoft.Office.Interop.Excel.Worksheet)oWB.ActiveSheet;
                    oSheet.Name = "Correspondence History";
                    string[] Cellsnames = { "a", "b", "c", "d", "e", "f", "g", "h" };
                    if (gvReportview != null)
                    {
                        if (gvReportview.Rows.Count > 0)
                        {
                            for (int j = 0; j < gvReportview.HeaderRow.Cells.Count; j++)
                            {
                                oRange = (Microsoft.Office.Interop.Excel.Range)oSheet.get_Range(Cellsnames[j] + (1).ToString(), Cellsnames[j] + (1).ToString());
                                oSheet.get_Range(Cellsnames[j] + (1).ToString(), Cellsnames[j] + (1).ToString()).EntireRow.Font.Bold = true;
                                oSheet.get_Range(Cellsnames[j] + (1).ToString(), Cellsnames[j] + (1).ToString()).EntireRow.Font.Size = 10;
                                oSheet.get_Range(Cellsnames[j] + (1).ToString(), Cellsnames[j] + (1).ToString()).EntireRow.Font.Name = "arial"; oRange.Borders.Color = System.Drawing.Color.Black.ToArgb();
                                // oSheet.get_Range(Cellsnames[j] + (1).ToString(), Cellsnames[j] + (1).ToString()).Interior.Pattern = Microsoft.Office.Interop.Excel.XlPattern.xlPatternGray50;
                                oRange.EntireColumn.ColumnWidth = 20; oRange.EntireColumn.RowHeight = 15;
                                oRange.EntireColumn.WrapText = true;
                                oRange = oSheet.get_Range(Cellsnames[j] + (1).ToString(), Cellsnames[j] + (1).ToString());
                                oRange.FormulaR1C1 = gvReportview.HeaderRow.Cells[j].Text;
                                oRange.HorizontalAlignment = 3;
                                oRange.VerticalAlignment = 3;
                            }
                            int k = 0; int m = 0;
                            foreach (GridViewRow gvrow in gvReportview.Rows)
                            {
                                k = m;
                                for (int i = 0; i < gvrow.Cells.Count; i++)
                                {

                                    oRange = (Microsoft.Office.Interop.Excel.Range)oSheet.get_Range(Cellsnames[i] + (k + 2).ToString(), Cellsnames[i] + (k + 2).ToString());
                                    //oSheet.get_Range(Cellsnames[i] + (k + 2).ToString(), Cellsnames[i] + (k + 2).ToString()).EntireRow.Font.Bold = true;
                                    oSheet.get_Range(Cellsnames[i] + (k + 2).ToString(), Cellsnames[i] + (k + 2).ToString()).EntireRow.Font.Size = 10;
                                    oSheet.get_Range(Cellsnames[i] + (k + 2).ToString(), Cellsnames[i] + (k + 2).ToString()).EntireRow.Font.Name = "arial";
                                    oRange.Borders.Color = System.Drawing.Color.Black.ToArgb();
                                    // oSheet.get_Range(Cellsnames[i] + (k + 2).ToString(), Cellsnames[i] + (k + 2).ToString()).Interior.Pattern = Microsoft.Office.Interop.Excel.XlPattern.xlPatternGray50;
                                    oRange.EntireColumn.ColumnWidth = 20; oRange.EntireColumn.RowHeight = 15;
                                    oRange.EntireColumn.WrapText = true;
                                    oRange = oSheet.get_Range(Cellsnames[i] + (k + 2).ToString(), Cellsnames[i] + (k + 2).ToString());
                                    string CellText = string.Empty;
                                    if (i == 0)
                                    {
                                        Label lblreferenceno = (Label)gvrow.FindControl("lblreferenceno");
                                        if (!string.IsNullOrEmpty(lblreferenceno.Text))
                                            CellText = lblreferenceno.Text;
                                        else
                                        {
                                            HyperLink lnkview = (HyperLink)gvrow.FindControl("lnkview");
                                            CellText = lnkview.Text;
                                        }
                                    }
                                    else if (i == 1)
                                    {
                                        Label lblreferenceno = (Label)gvrow.FindControl("lbltitle");
                                        if (!string.IsNullOrEmpty(lblreferenceno.Text))
                                            CellText = lblreferenceno.Text;
                                    }
                                    else if (i == 2)
                                    {
                                        Label lblreferenceno = (Label)gvrow.FindControl("lblsender");
                                        if (!string.IsNullOrEmpty(lblreferenceno.Text))
                                            CellText = lblreferenceno.Text;
                                    }
                                    else if (i == 3)
                                    {
                                        Label lblreferenceno = (Label)gvrow.FindControl("lblreceiveddate");
                                        if (!string.IsNullOrEmpty(lblreferenceno.Text))
                                            CellText = lblreferenceno.Text;
                                    }
                                    else if (i == 4)
                                    {
                                        Label lblreferenceno = (Label)gvrow.FindControl("lblsubject");
                                        if (!string.IsNullOrEmpty(lblreferenceno.Text))
                                            CellText = lblreferenceno.Text;
                                    }
                                    //else if (i == 5)
                                    //{
                                    //    Label lblreferenceno = (Label)gvrow.FindControl("lblreferenceno");
                                    //    if (!string.IsNullOrEmpty(lblreferenceno.Text))
                                    //        CellText = lblreferenceno.Text;
                                    //}
                                    oRange.FormulaR1C1 = CellText;//Adding datat to cell
                                    oRange.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;
                                    oRange.VerticalAlignment = 3;


                                }
                                m = m + 1;
                                k = m;
                            }
                        }
                    }

                    //oSheet.PageSetup.PaperSize = Microsoft.Office.Interop.Excel.XlPaperSize.xlPaperA4;
                    //oSheet.PageSetup.PrintGridlines = true;
                    oSheet = null;
                    oRange = null;
                    string temppath = System.IO.Path.GetTempPath();
                    if (File.Exists(temppath + "Correspondence Report.xlsx"))
                        File.Delete(temppath + "Correspondence Report.xlsx");
                    oXL.ActiveWorkbook.SaveCopyAs(temppath + "Correspondence Report.xlsx");


                    oWB.Close(Missing.Value, Missing.Value, Missing.Value);
                    oWB = null;
                    oXL.Quit();
                    releaseObject(oSheet);
                    releaseObject(oWB);
                    releaseObject(oXL);
                    ShowExcel(temppath + "Correspondence Report.xlsx");
                    if (File.Exists(temppath + "Correspondence Report.xlsx"))
                        File.Delete(temppath + "Correspondence Report.xlsx");
                }
                catch (Exception ex)
                {
                    lblMsg.ForeColor = System.Drawing.Color.Red;
                    lblMsg.Text = ex.Message.ToString();
                }
            });
        }
        private void releaseObject(object obj)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch (Exception ex)
            {
                obj = null;
                // MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
            }
            finally
            {
                GC.Collect();
            }
        }

        private void ShowExcel(string strS)
        {
            try
            {
                Response.ClearContent();
                Response.ClearHeaders();
                Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                Response.AddHeader("Content-Disposition", "attachment; filename=" + strS);
                //Response.AddHeader("Content-Disposition", "attachment; filename=ravi.xls");

                Response.TransmitFile(strS);
                Response.End();
                //Response.WriteFile(strS);
                Response.Flush();
                Response.Clear();
            }
            catch (Exception ex)
            {
                lblMsg.ForeColor = System.Drawing.Color.Red;
                lblMsg.Text = ex.Message.ToString();
            }
        }