如何使用列表表单中的代码创建PDF报表,而不是使用Microsoft Report Viewer

时间:2017-09-12 02:40:36

标签: c# asp.net pdf rdlc reportviewer

我正在使用Microsoft.Report.Viewer在我的ASP .NET WEB API应用程序中生成PDF。到目前为止,当我的报告直接从数据库获取数据时,没有问题。问题是,当我尝试在子报表中创建报表并且子报表数据是从列表表单中的代码获取时,我没有得到预期的结果。我所做的是使用此tutorial的子报表创建报表。但是当我生成PDF时,我收到的是此消息message

这是我的代码:

我的Web API生成PDF:

[Route("GeneratePDFForDailyProgram")]
    [HttpGet]
    [AllowAnonymous]
    public async Task<IHttpActionResult> GeneratePDFForDailyProgram(int id) {

        string guid = Guid.NewGuid().ToString();
        string fileName = string.Concat("Booking_No" + Convert.ToString(id) + "_" + guid.ToUpper() + ".pdf");
        string filePath = HttpContext.Current.Server.MapPath("~/Content/Temp/" + fileName);
        string name = Request.RequestUri.GetLeftPart(UriPartial.Authority) + System.Configuration.ConfigurationManager.ConnectionStrings[System.Configuration.ConfigurationManager.AppSettings["CUSTOMPORT"]];
        string name2 = Request.GetRequestContext().VirtualPathRoot;
        List<TourDestination> destination = new List<TourDestination>();

        TourTransactionSummaryViewModel summaryViewModel = new TourTransactionSummaryViewModel();

        try {

            //summaryViewModel = await CalcSummaryViewModel(transaction, summaryViewModel, db);

            summaryViewModel.DailyPrograms = DailyProgram(id);
            destination = TourDestination(summaryViewModel.DailyPrograms);

            List < Movement > movementList = summaryViewModel.DailyPrograms.FirstOrDefault().Movements.ToList();
            Reports.ReportGenerator.GeneratePDFForDailyProgram(summaryViewModel.DailyPrograms, destination, filePath);
            //await Reports.ReportGenerator.GeneratePDFForMovement(movementList,  filePath);


            HttpResponseMessage result = null;
            result = Request.CreateResponse(HttpStatusCode.OK);
            result.Content = new StreamContent(new FileStream(filePath, FileMode.Open));
            result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
            result.Content.Headers.ContentDisposition.FileName = fileName;

            result.Dispose();

            string convertedFilePath = filePath.Replace(@"\\", @"\");



        } catch (Exception ex) {

            return BadRequest(ex.Message);
        }

        return Ok(name + name2 + "/Content/Temp/" + fileName);
    }

从上面的代码中可以看出,我使用GeneratePDFForDailyProgram方法生成PDF。

这是我的GeneratePDFForDailyProgram方法:

public static bool GeneratePDFForDailyProgram(TourTransactionSummaryViewModel.DailyProgram[] dailyPrograms, List<TourDestination> destination , string filePath) {

        try {
            string binPath = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "bin");
            var assembly = Assembly.Load(System.IO.File.ReadAllBytes(binPath + "\\TripPlannerAPI.dll"));

            using (Stream stream = assembly.GetManifestResourceStream(DailyProgramReport)) {
                var viewer = new ReportViewer();
                viewer.LocalReport.EnableExternalImages = true;
                viewer.LocalReport.LoadReportDefinition(stream);

                Warning[] warnings;
                string[] streamids;
                string mimeType;
                string encoding;
                string filenameExtension;

                viewer.LocalReport.SubreportProcessing += new Microsoft.Reporting.WebForms.SubreportProcessingEventHandler(LocalReport_SubreportProcessing);
                viewer.LocalReport.DataSources.Add(new ReportDataSource("DailyProgram", dailyPrograms));


                byte[] bytes = viewer.LocalReport.Render(
                    "PDF", null, out mimeType, out encoding, out filenameExtension,
                    out streamids, out warnings);

                using (FileStream fs = new FileStream(filePath, FileMode.Create)) {
                    fs.Write(bytes, 0, bytes.Length);
                    fs.Flush();
                }

                stream.Flush();
            }
        } catch (Exception ex) {

            return false;
        }

        return true;
    }

要运行SubReport,我使用eventhandler代码:

private static void LocalReport_SubreportProcessing(object sender, SubreportProcessingEventArgs e) {

        DateTime movementDate = Convert.ToDateTime(e.Parameters[0].Values[0]);

        TourTransactionsController controller = new TourTransactionsController();

        var movement = controller.Movements();


        List<Movement> movementList = new List<Movement>();
        movementList.Add(new Movement {
            Destination = "TEST",
            MovementDescription = "TEST",
            DateTime =  Convert.ToDateTime("2017-09-25") //HARDCODE FOR TEST
        });

        e.DataSources.Clear();

        e.DataSources.Add(new Microsoft.Reporting.WebForms.ReportDataSource() {
            Name = "DSMovements",
            Value = movementList
        });

        //throw new NotImplementedException();
    }

我做了什么尝试:

  1. 检查子报告名称,并将其从报告名称更改为报告文件URL。仍然得到相同的消息。
  2. 直接生成子报告,而不是从主报告生成。子报表已成功生成。
  3. PS:当我调试我的代码,并在我的事件处理程序LocalReport_SubreportProcessing中放置一个断点时,调试时断点没有出现

    我的问题是:

    1. 为什么我的断点在事件处理程序上没有在调试时命中?
    2. 调试时没有遇到的事件处理程序是否可能是我收到消息The subreport 'MovementReport' could not be found at the specified location MovementReport. Please verify that the subreport has been published and that the name is correct.的原因?
    3. 我是否还有其他方法可以创建包含db数据的主报表,以及包含列表表单代码数据的子报表?
    4. 感谢任何帮助。

0 个答案:

没有答案