How to Export Report to PDF programmatically

Below is the code for exporting report to PDF format.

In the below function following parameters stands for :

viewer =Report Viewer Control object
exportType=export format say "PDF"
reportsTitle=Report name/title while exporting.

public bool ExportPDF(ReportViewer viewer, string exportType, string reportsTitle)

{

try

{

Warning[] warnings = null;

string[] streamIds = null;

string mimeType = string.Empty;

string encoding = string.Empty;

string extension = string.Empty;

string filetype = string.Empty;

// just gets the Report title... make your own method

//ReportViewer needs a specific type (not always the same as the extension)

 

filetype = exportType == "PDF" ? "PDF" : exportType;

byte[] bytes = viewer.ServerReport.Render(filetype, null, // deviceinfo not needed for csv

out mimeType, out encoding, out extension, out streamIds, out warnings);

//System.Web.HttpContext.Current.Response.Buffer = true;

//System.Web.HttpContext.Current.Response.Clear();

//System.Web.HttpContext.Current.Response.ContentType = mimeType;

//System.Web.HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + reportsTitle + "." + exportType);

//System.Web.HttpContext.Current.Response.BinaryWrite(bytes);

 

FileStream fs = new FileStream(Server.MapPath("~/GeneratedFiles/" + reportsTitle + "." + exportType), FileMode.OpenOrCreate);

 

fs.Write(bytes, 0, bytes.Length);

fs.Close();

 

// System.Web.HttpContext.Current.Response.Flush();

// System.Web.HttpContext.Current.Response.End();

}

catch( Exception ex)

{ 

}

return true;

}

 

Next Recommended Reading Exporting Data From DataTable To PDF