Monday, 22 October 2012

How to merge multiple pdf files in .net



         
Step: 1 Function for merge


public void MergePDFs(string[] fileNames, string outFile)
        {
            int pageOffset = 0;
            ArrayList master = new ArrayList();
            int f = 0;
            Document document = null;
            PdfCopy writer = null;
            while (f < (GetArrayOccupiedLenght(fileNames)-1)) //fileNames.Length-1
            {


                PdfReader reader = new PdfReader(fileNames[f]);
                reader.ConsolidateNamedDestinations();
                // we retrieve the total number of pages
                int n = reader.NumberOfPages;
                pageOffset += n;
                if (f == 0)
                {
                    // step 1: creation of a document-object
                    document = new Document(reader.GetPageSizeWithRotation(1));
                    // step 2: we create a writer that listens to the document
                    writer = new PdfCopy(document, new FileStream(outFile, FileMode.Create));
                    // step 3: we open the document
                    document.Open();
                }
                // step 4: we add content
                for (int i = 0; i < n; )
                {
                    ++i;
                    if (writer != null)
                    {
                        PdfImportedPage page = writer.GetImportedPage(reader, i);
                        writer.AddPage(page);
                    }
                }
                PRAcroForm form = reader.AcroForm;
                if (form != null && writer != null)
                {
                    writer.CopyAcroForm(reader);
                }
                f++;
            }
            // step 5: we close the document
            if (document != null)
            {
                document.Close();
            }
        }


Step2: How to Call

public void MyPDFs()
{
string[] files;
string MergedPath;

files[0] = "D:\abc.pdf";
files[1] = "D:\xyz.pdf";
files[2] = "D:\pqr.pdf";

MergedPath = "D:\MergedFile.pdf";
MergePDFs(files,MergedPath);
} 

Note : Don't forget to use the iTextSharp Namespace.

Tuesday, 9 October 2012

How to fast Export Datatable into Excel sheet in .net



Just Put this function and Pass argument as datatable in Your code
 

private void ExporttoExcelFast(DataTable table)
    {
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.ClearContent();
        HttpContext.Current.Response.ClearHeaders();
        HttpContext.Current.Response.Buffer = true;
        HttpContext.Current.Response.ContentType = "application/ms-excel";
        HttpContext.Current.Response.Write(@"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.0 Transitional//EN"">");
        HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=DAS.xls");

        HttpContext.Current.Response.Charset = "utf-8";
        HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1250");
        //sets font
        HttpContext.Current.Response.Write("<font style='font-size:10.0pt; font-family:Calibri;'>");
        HttpContext.Current.Response.Write("<BR><BR><BR>");
        //sets the table border, cell spacing, border color, font of the text, background, foreground, font height
        HttpContext.Current.Response.Write("<Table border='1' bgColor='#ffffff' " +
          "borderColor='#000000' cellSpacing='0' cellPadding='0' " +
          "style='font-size:10.0pt; font-family:Calibri; background:white;'> <TR>");
        //am getting my grid's column headers
        int columnscount = table.Columns.Count;

        for (int j = 0; j < columnscount; j++)
        {      //write in new column
            HttpContext.Current.Response.Write("<Td  bgcolor='#6699cc'>");
            //Get column headers  and make it as bold in excel columns
            HttpContext.Current.Response.Write("<B>");
            HttpContext.Current.Response.Write(table.Columns[j].ColumnName);
            HttpContext.Current.Response.Write("</B>");
            HttpContext.Current.Response.Write("</Td>");
        }
        HttpContext.Current.Response.Write("</TR>");
        foreach (DataRow row in table.Rows)
        {//write in new row
            HttpContext.Current.Response.Write("<TR>");
            for (int i = 0; i < table.Columns.Count; i++)
            {

                if (row[i].ToString() == "01/01/1754")
                {
                    if (table.Rows.IndexOf(row) % 2 == 0)
                    {
                        HttpContext.Current.Response.Write("<Td>");
                        HttpContext.Current.Response.Write(" ");
                        HttpContext.Current.Response.Write("</Td>");
                    }
                    else
                    {
                        HttpContext.Current.Response.Write("<Td bgcolor='#dcf2f8'>");
                        HttpContext.Current.Response.Write(" ");
                        HttpContext.Current.Response.Write("</Td>");
                    }
                }
                else
                {
                    if (table.Rows.IndexOf(row) % 2 == 0)
                    {
                        HttpContext.Current.Response.Write("<Td>");
                        HttpContext.Current.Response.Write(row[i].ToString());
                        HttpContext.Current.Response.Write("</Td>");
                    }
                    else
                    {
                        HttpContext.Current.Response.Write("<Td bgcolor='#dcf2f8'>");
                        HttpContext.Current.Response.Write(row[i].ToString());
                        HttpContext.Current.Response.Write("</Td>");
                    }
                }
            }

            HttpContext.Current.Response.Write("</TR>");
        }
        HttpContext.Current.Response.Write("</Table>");
        HttpContext.Current.Response.Write("</font>");
        HttpContext.Current.Response.Flush();
        HttpContext.Current.Response.End();
    }

Friday, 28 September 2012

How to show Excel sheet data in Web Page using Asp.net



Advantage : Some times it happens that, we need to show data in very large quantity, which is not possible with GridView. Suppose we want to bind 15000 rows with Gridview without paging, So it will chop our server.Now in that case this is best choice to Export Your data in Excel Sheet then bind with browser using IFRAME.


Default.aspx



·         When we shall Click on Button the Excel sheet will be show as  
   given in your browser.


·         We have taken a iframe, and excel sheet is showing in IFrame.



·        Write Given below code in your Default.aspx.cs file

Note: I have used “Microsoft.Office.Interop.Excel, Microsoft.Office.Interop.Word” References here.

--*******************************************************--

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Excel = Microsoft.Office.Interop.Excel;
using word = Microsoft.Office.Interop.Word;

public partial class _Default : System.Web.UI.Page
{
 #region Global Variabes

    public string Message = string.Empty;           // To store the Error or Message
    private word.ApplicationClass OfficeWord;       // The Interop Object for Word
    private Excel.ApplicationClass  OfficeExcel;     // The Interop Object for Excel
    object Unknown = Type.Missing;                     // For passing Empty values
    public enum StatusType { SUCCESS, FAILED };     // To Specify Success or Failure Types
    public StatusType Status;                       // To know the Current Status

 #endregion


    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {

        string strFilePath = Server.MapPath(@"ConvertedFileLocation\");
        string strFile = "Test.xlsx";
        string[] File = strFile.Split('.');
        string strExtension = File[1].ToString();
        string strUrl = "http://" + Request.Url.Authority + "/Ecel/ConvertedFileLocation/";

        string Filename = strFilePath + strFile.Split('.')[0] + ".html";

        if (System.IO.File.Exists(Filename))
        {
            System.IO.File.Delete(Filename);
        }

        ConvertExcelToHTML(strFilePath + strFile, strFilePath + strFile.Split('.')[0] + ".html");

        ifr.Attributes["src"] = strUrl + strFile.Split('.')[0] + ".html";

    }
    public void ConvertWordToHTML(object Source, object Target)
    {
        if (OfficeWord == null)                         // Check for the prior instance of the OfficeWord Object
            OfficeWord = new word.ApplicationClass();

        try
        {
            // To suppress window display the following code will help
            OfficeWord.Visible = false;
            OfficeWord.Application.Visible = false;
            OfficeWord.WindowState = word.WdWindowState.wdWindowStateMinimize;



            OfficeWord.Documents.Open(ref Source, ref Unknown,
                 ref Unknown, ref Unknown, ref Unknown,
                 ref Unknown, ref Unknown, ref Unknown,
                 ref Unknown, ref Unknown, ref Unknown,
                 ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown);

            object format = word.WdSaveFormat.wdFormatHTML;

            OfficeWord.ActiveDocument.SaveAs(ref Target, ref format,
                    ref Unknown, ref Unknown, ref Unknown,
                    ref Unknown, ref Unknown, ref Unknown,
                    ref Unknown, ref Unknown, ref Unknown,
                    ref Unknown, ref Unknown, ref Unknown,
                   ref Unknown, ref Unknown);

            Status = StatusType.SUCCESS;
            Message = Status.ToString();
        }
        catch (Exception e)
        {
            Message = "Error :" + e.Message.ToString().Trim();
        }
        finally
        {
            if (OfficeWord != null)
            {
                OfficeWord.Documents.Close(ref Unknown, ref Unknown, ref Unknown);
                OfficeWord.Quit(ref Unknown, ref Unknown, ref Unknown);
            }
        }
    }

    public void ConvertExcelToHTML(string Source, string Target)
    {
        if (OfficeExcel == null) OfficeExcel = new Excel.ApplicationClass();

        try
        {
            OfficeExcel.Visible = false;
            OfficeExcel.Application.Visible = false;
            OfficeExcel.WindowState = Excel.XlWindowState.xlMinimized;

            OfficeExcel.Workbooks.Open(Source, Unknown,
                 Unknown, Unknown, Unknown,
                 Unknown, Unknown, Unknown,
                 Unknown, Unknown, Unknown,
                 Unknown, Unknown, Unknown, Unknown);

            object format = Excel.XlFileFormat.xlHtml;

            OfficeExcel.Workbooks[1].SaveAs(Target, format,
                    Unknown, Unknown, Unknown,
                    Unknown, Excel.XlSaveAsAccessMode.xlExclusive, Unknown,
                    Unknown, Unknown, Unknown,
                    Unknown);

            Status = StatusType.SUCCESS;
            Message = Status.ToString();

        }
        catch (Exception e)
        {
            Message = "Error :" + e.Message.ToString().Trim();
        }
        finally
        {
            if (OfficeExcel != null)
            {
                OfficeExcel.Workbooks.Close();
                OfficeExcel.Quit();
            }
        }
    }
}

--*******************************************************--