简体   繁体   English

在没有报表查看器的情况下在网页中呈现SSRS 2008报表

[英]Render SSRS 2008 Report in web page without Report Viewer

I have a web app written in C# that I need to be able to render an SSRS report on an aspx page without using the Report Viewer control. 我有一个用C#编写的Web应用程序,我需要能够在aspx页面上呈现SSRS报告, 而无需使用Report Viewer控件。

As HTML inside a div tag would be perfect. 由于div标签内的HTML是完美的。 I have the app attached to my SSRS instance via ReportingService2010 reference. 我已通过ReportingService2010参考将应用程序附加到我的SSRS实例。

I've found some examples online but are for ReportingServices2005 and couldn't port them over. 我在网上找到了一些示例,但这些示例适用于ReportingServices2005 ,无法将其移植过来。

How can I do this? 我怎样才能做到这一点?

I pulled this out of a project I put together about a year ago. 我从大约一年前制定的项目中撤出了这个计划。

A few key points: 一些要点:

  • you need to pass credentials to the report server. 您需要将凭据传递到报表服务器。
  • you need to create an images path so that any images in your report are rendered and displayed in the html Report/GraphFiles/ "this should be relative to your app url" 您需要创建一个图像路径,以便报表中的所有图像都可以呈现并显示在html Report / GraphFiles /中。“这应该相对于您的应用程序网址”
  • and if your report has any parameters you will need to add them. 并且如果您的报告中包含任何参数,则需要添加它们。
  • you will definitely need to tweek the code to get it going. 您肯定需要花些时间来执行代码。

it uses the ReportExecutionService reference, you will have to play around with it but the nuts and bolts should all be here. 它使用ReportExecutionService参考,您将不得不使用它,但基本要在这里。

i'd really love to spend time cleaning it up a bit but i dont have the time sorry, i hope it helps 我真的很想花一点时间清理它,但是我没有时间对不起,我希望它会有所帮助

class RenderReport
    {

        public struct ReportServerCreds
            {
                public string UserName { get; set; }
                public string Password { get; set; }
                public string Domain { get; set; }

            }

            public ReportServerCreds GetReportCreds()
            {

                ReportServerCreds rsc = new ReportServerCreds();
                rsc.UserName = ConfigurationManager.AppSettings["reportserveruser"].ToString();
                rsc.Password = ConfigurationManager.AppSettings["reportserverpassword"].ToString();
                rsc.Domain = ConfigurationManager.AppSettings["reportserverdomain"].ToString();

                return rsc;
            }

           public enum SSRSExportType
            { 
                HTML,PDF
            }

            public string RenderReport(string reportpath,SSRSExportType ExportType)
            {
                using (ReportExecutionService.ReportExecutionServiceSoapClient res = new   ReportExecutionService.ReportExecutionServiceSoapClient("ReportExecutionServiceSoap"))
                {

                    ReportExecutionService.ExecutionHeader ExecutionHeader = new ReportExecutionService.ExecutionHeader();
                    ReportExecutionService.TrustedUserHeader TrusteduserHeader = new ReportExecutionService.TrustedUserHeader();

                    res.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;

                    ReportServerCreds rsc = GetReportCreds();
                    res.ClientCredentials.Windows.ClientCredential.Domain = rsc.Domain;
                    res.ClientCredentials.Windows.ClientCredential.UserName = rsc.UserName;
                    res.ClientCredentials.Windows.ClientCredential.Password = rsc.Password;


                    res.Open();
                    ReportExecutionService.ExecutionInfo ei = new ReportExecutionService.ExecutionInfo();

                    string format =null;
                    string deviceinfo =null;
                    string mimetype = null;

                    if (ExportType.ToString().ToLower() == "html")
                    {
                        format = "HTML4.0";
                        deviceinfo = @"<DeviceInfo><StreamRoot>/</StreamRoot><HTMLFragment>True</HTMLFragment></DeviceInfo>";
                    }
                    else if (ExportType.ToString().ToLower() == "pdf")
                    {
                        format = "PDF";
                        mimetype = "";
                    }


                    byte[] results = null;
                    string extension = null;
                    string Encoding = null;
                    ReportExecutionService.Warning[] warnings;
                    string[] streamids = null;
                    string historyid = null;
                    ReportExecutionService.ExecutionHeader Eheader;
                    ReportExecutionService.ServerInfoHeader serverinfoheader;
                    ReportExecutionService.ExecutionInfo executioninfo;



                    // Get available parameters from specified report.
                    ParameterValue[] paramvalues = null;
                    DataSourceCredentials[] dscreds = null;
                    ReportParameter[] rparams = null;

                    using (ReportService.ReportingService2005SoapClient lrs = new ReportService.ReportingService2005SoapClient("ReportingService2005Soap"))
                    {


                        lrs.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
                        lrs.ClientCredentials.Windows.ClientCredential.Domain = rsc.Domain;
                        lrs.ClientCredentials.Windows.ClientCredential.UserName = rsc.UserName;
                        lrs.ClientCredentials.Windows.ClientCredential.Password = rsc.Password;


                        lrs.GetReportParameters(reportpath,historyid,false,paramvalues,dscreds,out rparams);

                    }



                    // Set report parameters here
                    //List<ReportExecutionService.ParameterValue> parametervalues = new List<ReportExecutionService.ParameterValue>();

                    //string enumber = Session["ENumber"] as string;
                    //parametervalues.Add(new ReportExecutionService.ParameterValue() { Name = "ENumber", Value = enumber });

                    //if (date != null)
                    //{
                    //    DateTime dt = DateTime.Today;
                        //parametervalues.Add(new ReportExecutionService.ParameterValue() { Name = "AttendanceDate", Value = dt.ToString("MM/dd/yyyy")});
                    //}

                    //if (ContainsParameter(rparams, "DEEWRID"))
                    //{
                        //parametervalues.Add(new ReportExecutionService.ParameterValue() { Name = "DEEWRID", Value = deewrid });
                    //}

                    //if (ContainsParameter(rparams, "BaseHostURL"))
                    //{
//                        parametervalues.Add(new ReportExecutionService.ParameterValue() { Name = "BaseHostURL", Value = string.Concat("http://", Request.Url.Authority) });
                    //}


                    //parametervalues.Add(new ReportExecutionService.ParameterValue() {Name="AttendanceDate",Value=null });
                    //parametervalues.Add(new ReportExecutionService.ParameterValue() { Name = "ENumber", Value = "E1013" });



                    try
                    {

                        Eheader = res.LoadReport(TrusteduserHeader, reportpath, historyid, out serverinfoheader, out executioninfo);
                        serverinfoheader = res.SetExecutionParameters(Eheader, TrusteduserHeader, parametervalues.ToArray(), null, out executioninfo);
                        res.Render(Eheader, TrusteduserHeader, format, deviceinfo, out results, out extension, out mimetype, out Encoding, out warnings, out streamids);

                        string exportfilename = string.Concat(enumber, reportpath);

                        if (ExportType.ToString().ToLower() == "html")
                        {
                            //write html
                            string html = string.Empty;
                            html = System.Text.Encoding.Default.GetString(results);

                            html = GetReportImages(res, Eheader, TrusteduserHeader, format, streamids, html);

                            return html;
                        }
                        else if (ExportType.ToString().ToLower() == "pdf")
                        {
                            //write to pdf


                            Response.Buffer = true;
                            Response.Clear();
                            Response.ContentType = mimetype;



                            //Response.AddHeader("content-disposition", string.Format("attachment; filename={0}.pdf", exportfilename));
                            Response.BinaryWrite(results);
                            Response.Flush();
                            Response.End();

                        }


                    }
                    catch (Exception e)
                    {
                        Response.Write(e.Message);
                    }
                }

            }


            string GetReportImages(ReportExecutionService.ReportExecutionServiceSoapClient res, 
                                   ReportExecutionService.ExecutionHeader EHeader,
                                    ReportExecutionService.TrustedUserHeader tuh,
                                   string reportFormat, string[] streamIDs, string html)
            {
                if (reportFormat.Equals("HTML4.0") && streamIDs.Length > 0)
                {
                    string devInfo;
                    string mimeType;
                    string Encoding;
                    int startIndex;
                    int endIndex;
                    string fileExtension = ".jpg";

                    string SessionId;

                    Byte[] image;

                    foreach (string streamId in streamIDs)
                    {
                        SessionId = Guid.NewGuid().ToString().Replace("}", "").Replace("{", "").Replace("-", "");
                        //startIndex = html.IndexOf(streamId);
                        //endIndex = startIndex + streamId.Length;

                        string reportreplacementname = string.Concat(streamId, "_", SessionId, fileExtension);
                        html = html.Replace(streamId, string.Concat(@"Report\GraphFiles\", reportreplacementname));


                        //html = html.Insert(endIndex, fileExtension);
                        //html = html.Insert(startIndex, @"Report/GraphFiles/" + SessionId + "_");

                        devInfo = "";
                        //Image = res.RenderStream(reportFormat, streamId, devInfo, out encoding, out mimeType);
                        res.RenderStream(EHeader,tuh, reportFormat, streamId, devInfo, out image , out Encoding, out mimeType);



                        System.IO.FileStream stream = System.IO.File.OpenWrite(HttpContext.Current.Request.PhysicalApplicationPath + "Report\\GraphFiles\\" + reportreplacementname);
                        stream.Write(image, 0, image.Length);
                        stream.Close();
                        mimeType = "text/html";
                    }
                }

                return html;
            }

            bool ContainsParameter(ReportParameter[] parameters, string paramname)
            {
                    if(parameters.Where(i=>i.Name.Contains(paramname)).Count() != 0)
                    {
                        return true;
                    }
                    return false;
                }
    }

To Execute: 执行:

first parameter is the location of the report on the server. 第一个参数是报表在服务器上的位置。 the second is a SSRSExportType enum 第二个是SSRSExportType枚举

RenderReport("ReportPathOnServer",SSRSExportType.HTML);

If you are just trying to show the HTML render of a report and you want it to look like a native object to the application without any parameters or toolbar, then you could call the URL for the report directly and include "&rc:Toolbar=false" in the URL. 如果您只是试图显示报告的HTML呈现,并且希望它看起来像应用程序的本机对象,而没有任何参数或工具栏,则可以直接调用报告的URL并包含“&rc:Toolbar = false” ”中的“”。 This will hide the toolbar for the Report Viewer control. 这将隐藏“报表查看器”控件的工具栏。 This method is described under the URL Access Parameter Reference msdn article . URL访问参数参考msdn文章下介绍了此方法。 Not exactly what you asked for, but it may achieve the purpose. 并非完全符合您的要求,但可以达到目的。

Here's a sample call that omits the HTML and Body sections if you are embedding the results in an existing HTML document: 如果将结果嵌入到现有的HTML文档中,那么以下示例调用将忽略HTML和Body部分:

http://ServerName/ReportServer?%2fSome+Folder%2fSome+Report+Name&rs:Command=Render&rc:Toolbar=false&rc:HTMLFragment=true

Definitely an old question but if you're using ASP.NET MVC you could try this open source solution . 绝对是一个老问题,但是如果您使用的是ASP.NET MVC,则可以尝试此开源解决方案 It uses an HTML helper and renders an .aspx page in an iframe. 它使用HTML帮助器,并在iframe中呈现.aspx页。 The repo has a server-side, local render, and anonymous example. 存储库有一个服务器端,本地渲染和匿名示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM