Wednesday, February 18, 2009

Exporting SSRS Report to Image file

Hi All,

Here I am putting a piece of code which exports SQL Server Reporting Service Report an Image file of type GIF. You can also export to other image file types as well.
Basically, we need to set DeviceInfo according to our requirement and pass that device info to Report's rendering extension mechanism.

string reportType = "Image";
string mimeType;
string encoding;
string fileNameExtension;

string deviceInfo = String.Format(@"
<DeviceInfo>
<OutputFormat>GIF</OutputFormat>
<PageWidth>{0}</PageWidth>
<PageHeight>{1}</PageHeight>
<MarginTop>{2}</MarginTop>
<MarginLeft>{3}</MarginLeft>
<MarginRight>{4}</MarginRight>
<MarginBottom>{5}</MarginBottom>
</DeviceInfo>",
"11in",
"8in",
"0in",
"0in",
"0in",
"0in"
);
Warning[] warnings;
string[] streams;
byte[] renderedBytes;

//Render the report
renderedBytes = reportViewer1.LocalReport.Render(
reportType,
deviceInfo,
out mimeType,
out encoding,
out fileNameExtension,
out streams,
out warnings);

string file = "C:\\MyImage" + "." + fileNameExtension;
Stream streamReportImage = new FileStream(file, FileMode.Create);
streamReportImage.Write(renderedBytes, 0, renderedBytes.Length);
streamReportImage.Position = 0;


Here you can see that, when we set OutPutFormat to GIF then, Render method returns us file extension accordingly which we can use the rendered bytes to output to a stream.

You can find more infromation about DeviceInfo for different output format on below link
Ref: http://msdn.microsoft.com/en-us/library/ms155397.aspx

Cheers,