вторник, 18 сентября 2012 г.

How to render client report definition files (.rdlc) directly to the Response stream without preview

ReportViewer control is normally used to open a report definition file, process it and load it into the viewing area.
The simple method below allows you to render the report directly to the response stream without using the ReportViewer control. This might be useful in cases where you want to render a non interactive report.
The example below renders the report in PDF format. The other report types available when using the LocalReport.Render method are “Excel”and “Image”.

/// References:
private void RenderReport() {
    LocalReport localReport = new LocalReport();
    localReport.ReportPath = Server.MapPath("~/Report.rdlc");
    //A method that returns a collection for our report
    //Note: A report can have multiple data sources
    List<Employee> employeeCollection = GetData();

    //Give the collection a name (EmployeeCollection) so that we can reference it in our report designer
    ReportDataSource reportDataSource = new ReportDataSource("EmployeeCollection", employeeCollection);

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

    //The DeviceInfo settings should be changed based on the reportType
    string deviceInfo =
    "" +
    "  PDF" +
    "  8.5in" +
    "  11in" +
    "  0.5in" +
    "  1in" +
    "  1in" +
    "  0.5in" +

    Warning[] warnings;
    string[] streams;
    byte[] renderedBytes;

    //Render the report
    renderedBytes = localReport.Render(
        out mimeType,
        out encoding,
        out fileNameExtension,
        out streams,
        out warnings);

    //Clear the response stream and write the bytes to the outputstream
    //Set content-disposition to "attachment" so that user is prompted to take an action
    //on the file (open or save)
    Response.ContentType = mimeType;
    Response.AddHeader("content-disposition""attachment; filename=foo." + fileNameExtension);


Note that if you change the ReportType in the Render method, you will also have to change the DeviceInfo settings. 

Комментариев нет: