Generating PDF using SSRS Reports programmatically

ReportViewer is a good tool to generate report file on fly in pdf / excel format in asp.net web application.

protected void btn_Click(object sender, EventArgs e)
{
   
//create instance to ReportViewer control

    Microsoft.Reporting.WebForms.ReportViewer ReportViewer1 =
       
new Microsoft.Reporting.WebForms.ReportViewer();

    //set ProcessingMode to ReportViewer either Remote/Local

    ReportViewer1.ProcessingMode =
        Microsoft.Reporting.WebForms.
ProcessingMode.Remote;

     //provide Report Server Url

    ReportViewer1.ServerReport.ReportServerUrl =
       
new Uri("http://venkateswarlu/ReportServer");

    /*Note: For loca report there is no ReportServerUrl property,
    it is in local solution folder, only report path is enough*/

    //provide Report Path

    ReportViewer1.ServerReport.ReportPath
        =
"/MyReports/MyReportName";

    //creating Report Parameters collection

    Microsoft.Reporting.WebForms.ReportParameter[] rptParams =
       
new Microsoft.Reporting.WebForms.ReportParameter[3];
    rptParams[0] =
       
new Microsoft.Reporting.WebForms.ReportParameter("ID", "1729");

    //parameter name - ID, value - 1729

    rptParams[1] =
       
new Microsoft.Reporting.WebForms.ReportParameter("Name", "Cherukuri");

    //setting Parameters to report

    ReportViewer1.ServerReport.SetParameters(rptParams);

    //declare variable need to render report

    //in parameters

    string format = "PDF",
        devInfo =
@"<DeviceInfo><Toolbar>True</Toolbar></DeviceInfo>";

    //out parameters

    string mimeType = "",
        encoding =
"",
        fileNameExtn =
"";
   
string[] stearms = null;
    Microsoft.Reporting.WebForms.
Warning[] warnings = null;

    byte[] result = null;

    try
    {
       
//render report, it will returns bite array

        result = ReportViewer1.ServerReport.Render(format,
            devInfo,
out mimeType, out encoding,
           
out fileNameExtn, out stearms, out warnings);

        //create file with require legth

        FileStream stream = File.Create(Server.MapPath("~/Reports/ch.PDF"), result.Length);

        //write file with rendered result

        stream.Write(result, 0, result.Length);

        //close stream

        stream.Close();
    }
   
catch (Exception ex)
    {

    }
}