I find myself doing alot of web based reporting for the current project that I am doing at the moment, which is no surprise, as the application that I am writing is basically a data-mining tool. One thing that has saved me alot of time is the reporting tools that come packaged with Visual Studio 8.
I like the way that the reporting services allows you to simply add a control to your web page, and suddenly, you can view the report on your web page. But what if you don’t want to show the form, or have something that is easier to print out, the ReportViewer control is just a little too tricky to use for most of my users. Fortunately, there is a way to print a PDF or Excel spreadsheet directly, without having to have the control placed on your page.
This method used the ReportViewer.LocalReport.Render() method, which simply draws the report, and returns you the bytes for whichever format that you choose. Here’s an example of how to draw to PDF:
//Includes
using System.Data;
using System.Collections.Generic;
using Microsoft.Reporting.WebForms;
public void GenerateReport(
String reportPath,
List paramaters,
String dataSourceName,
DataTable reportData,
String fileName)
{
// Definitions-a-plenty
string mimeType, encoding, extension;
Warning[] warnings;
string[] streamids;
byte[] bytes;
ReportViewer reportViewer = new ReportViewer();
// Add in the report data
reportViewer.LocalReport.ReportPath = reportPath;
reportViewer.LocalReport.SetParameters(paramaters);
reportViewer.LocalReport.DataSources.Add(new ReportDataSource(dataSourceName, reportData));
reportViewer.LocalReport.Refresh();
// Render the report to PDF
bytes = reportViewer.LocalReport.Render(
"PDF",
null,
out mimeType,
out encoding,
out extension,
out streamids,
out warnings);
// Finally, write the bytes directly to the output
// stream
//
// This should cause your browser to recognise a PDF
// coming out, rather than a web page
//
// NOTE: Will not work correctly if you have already
// written to the output stream, as it does
// things with page headers
Response.AddHeader("Content-Disposition", "attachment; filename="+fileName+extension);
Response.ContentType = mimeType;
Response.OutputStream.Write(bytes, 0, bytes.Length);
Response.End();
}


