Technology For Your Business For Your Life

Monday, September 12, 2011

View a Reporting Services report in PDF format with the click of a button

I recently had a requirement to allow users of a website  to view their reports in PDF format using Microsoft Reporting Services.
I had the report designed as a .rdlc file but just needed the c# code to send the report straight to pdf.
This is the code I used to solve this task.

LocalReport localReport = new LocalReport();
            localReport.ReportPath = Server.MapPath("..\\Report\\YourReport.rdlc");
            localReport.EnableExternalImages = true;
            ReportDataSource reportDataSource = new ReportDataSource("DataSet1", q.GetData(ID));
            localReport.DataSources.Add(reportDataSource);
    

          string reportType = "PDF";
          string mimeType;
          string encoding;
          string fileNameExtension;
          string deviceInfo =
    "<DeviceInfo>" +
    "  <OutputFormat>PDF</OutputFormat>" +
    "  <PageWidth>9.5in</PageWidth>" +
    "  <PageHeight>11in</PageHeight>" +
    "  <MarginTop>0.5in</MarginTop>" +
    "  <MarginLeft>1in</MarginLeft>" +
    "  <MarginRight>1in</MarginRight>" +
    "  <MarginBottom>0.5in</MarginBottom>" +
    "</DeviceInfo>";
          Warning[] warnings;
          string[] streams;
          byte[] renderedBytes;

          //Render the report
          renderedBytes = localReport.Render(
              reportType,
              deviceInfo,
              out mimeType,
              out encoding,
              out fileNameExtension,
              out streams,
              out warnings);
          Response.Clear();
          Response.ContentType = mimeType;
          Response.AddHeader("content-disposition", "attachment; filename=quote." + fileNameExtension);
          Response.BinaryWrite(renderedBytes);
          Response.End();

No comments:

Post a Comment