【问题标题】:Creating a PDF from a RDLC Report in the Background在后台从 RDLC 报告创建 PDF
【发布时间】:2011-02-10 16:05:35
【问题描述】:

我正在运行一个月末流程,并希望让它自动创建一些当时需要创建的报告。我正在使用 rdlc 报告。有没有办法在后台从 RDLC 报告自动创建 PDF?

【问题讨论】:

    标签: c# pdf reportviewer rdlc


    【解决方案1】:

    这很容易做到,您可以将报告呈现为 PDF,并将生成的字节数组作为 PDF 文件保存在磁盘上。要在后台执行此操作,更多的是关于您的应用程序是如何编写的问题。您可以只启动一个新线程,或使用 BackgroundWorker(如果这是一个 WinForms 应用程序)等。当然,可能需要注意多线程问题。

    Warning[] warnings;
    string[] streamids;
    string mimeType;
    string encoding;
    string filenameExtension;
    
    byte[] bytes = reportViewer.LocalReport.Render(
        "PDF", null, out mimeType, out encoding, out filenameExtension,
        out streamids, out warnings);
    
    using (FileStream fs = new FileStream("output.pdf", FileMode.Create))
    {
        fs.Write(bytes, 0, bytes.Length);
    }
    

    【讨论】:

    • 那么我是否只使用通用的 ReportViewer(不是任何形式的)?
    • 是的。事实上,您可以只实例化一个LocalReport 对象(使用其默认构造函数,然后设置ReportPath 或ReportEmbeddedResource 属性)并单独使用它。使用仅在内存中的 ReportViewer 来利用其导出/渲染功能是很常见的
    • 为什么会出现“尚未指定报表的报表定义”?
    • @bipartite 你需要viewer.LocalReport.ReportPath = "RdlcFiles/TagCount.rdlc";
    【解决方案2】:

    您可以使用以下代码在后台生成 pdf 文件,就像单击按钮一样,然后会在浏览器中弹出 SaveAs 和取消选项。

    Warning[] warnings;
            string[] streamIds;
            string mimeType = string.Empty;
            string encoding = string.Empty;`enter code here`
            string extension = string.Empty;
            DataSet dsGrpSum, dsActPlan, dsProfitDetails,
                dsProfitSum, dsSumHeader, dsDetailsHeader, dsBudCom = null;
    
        enter code here
    
    //This is optional if you have parameter then you can add parameters as much as you want
    ReportParameter[] param = new ReportParameter[5];
                param[0] = new ReportParameter("Report_Parameter_0", "1st Para", true);
                param[1] = new ReportParameter("Report_Parameter_1", "2nd Para", true);
                param[2] = new ReportParameter("Report_Parameter_2", "3rd Para", true);
                param[3] = new ReportParameter("Report_Parameter_3", "4th Para", true);
                param[4] = new ReportParameter("Report_Parameter_4", "5th Para");
    
                DataSet  dsData= "Fill this dataset with your data";
                ReportDataSource rdsAct = new ReportDataSource("RptActDataSet_usp_GroupAccntDetails", dsActPlan.Tables[0]);
                ReportViewer viewer = new ReportViewer();
                viewer.LocalReport.Refresh();
                viewer.LocalReport.ReportPath = "Reports/AcctPlan.rdlc"; //This is your rdlc name.
                viewer.LocalReport.SetParameters(param);
                viewer.LocalReport.DataSources.Add(rdsAct); // Add  datasource here         
                byte[] bytes = viewer.LocalReport.Render("PDF", null, out mimeType, out encoding, out extension, out streamIds, out warnings);
                // byte[] bytes = viewer.LocalReport.Render("Excel", null, out mimeType, out encoding, out extension, out streamIds, out warnings);
                // Now that you have all the bytes representing the PDF report, buffer it and send it to the client.          
                // System.Web.HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
                Response.Buffer = true;
                Response.Clear();
                Response.ContentType = mimeType;
                Response.AddHeader("content-disposition", "attachment; filename= filename" + "." + extension);
                Response.OutputStream.Write(bytes, 0, bytes.Length); // create the file  
                Response.Flush(); // send it to the client to download  
                Response.End();
    

    【讨论】:

    • 你试过发送参数吗?我不断收到:An error occurred during local report processing.at Microsoft.Reporting.WebForms.LocalReport.EnsureExecutionSession() at Microsoft.Reporting.WebForms.LocalReport.SetParameters(IEnumerable`1 parameters)
    【解决方案3】:

    下面的代码对我来说很好用,当然感谢上面的 cmets。您可以添加报表查看器并更改 visible=false 并在提交按钮上使用以下代码:

    protected void Button1_Click(object sender, EventArgs e)
    {
        Warning[] warnings;
        string[] streamIds;
        string mimeType = string.Empty;
        string encoding = string.Empty;
        string extension = string.Empty;
        string HIJRA_TODAY = "01/10/1435";
        ReportParameter[] param = new ReportParameter[3];
        param[0] = new ReportParameter("CUSTOMER_NUM", CUSTOMER_NUMTBX.Text);
        param[1] = new ReportParameter("REF_CD", REF_CDTB.Text);
        param[2] = new ReportParameter("HIJRA_TODAY", HIJRA_TODAY);
    
        byte[] bytes = ReportViewer1.LocalReport.Render(
            "PDF", 
            null, 
            out mimeType, 
            out encoding, 
            out extension, 
            out streamIds, 
            out warnings);
    
        Response.Buffer = true;
        Response.Clear();
        Response.ContentType = mimeType;
        Response.AddHeader(
            "content-disposition", 
            "attachment; filename= filename" + "." + extension);
        Response.OutputStream.Write(bytes, 0, bytes.Length); // create the file  
        Response.Flush(); // send it to the client to download  
        Response.End();
    }    
    

    【讨论】:

      【解决方案4】:

      您无需在任何地方使用 reportViewer 控件 - 您可以动态创建 LocalReport:

      var lr = new LocalReport
      {
          ReportPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? @"C:\", "Reports", "PathOfMyReport.rdlc"),
          EnableExternalImages = true
      };
      
      lr.DataSources.Add(new ReportDataSource("NameOfMyDataSet", model));
      
      string mimeType, encoding, extension;
      
      Warning[] warnings;
      string[] streams;
      var renderedBytes = lr.Render
          (
              "PDF",
              @"<DeviceInfo><OutputFormat>PDF</OutputFormat><HumanReadablePDF>False</HumanReadablePDF></DeviceInfo>",
              out mimeType,
              out encoding,
              out extension,
              out streams,
              out warnings
          );
      
      var saveAs = string.Format("{0}.pdf", Path.Combine(tempPath, "myfilename"));
      
      var idx = 0;
      while (File.Exists(saveAs))
      {
          idx++;
          saveAs = string.Format("{0}.{1}.pdf", Path.Combine(tempPath, "myfilename"), idx);
      }
      
      using (var stream = new FileStream(saveAs, FileMode.Create, FileAccess.Write))
      {
          stream.Write(renderedBytes, 0, renderedBytes.Length);
          stream.Close();
      }
      
      lr.Dispose();
      

      您还可以添加参数:(lr.SetParameter()),处理子报告:(lr.SubreportProcessing+=YourHandler),或几乎任何您能想到的东西。

      【讨论】:

      • 如果想要获取格式化的 pdf 文件,我们需要报告查看器。比如说...我需要以 pdf 格式获取我的网页的精确副本,包括格式、颜色和显示,然后需要先创建一个模板,然后用数据集填充它。
      【解决方案5】:
       private void PDFExport(LocalReport report)
          {           
              string[] streamids;
              string minetype;
              string encod;
              string fextension;
              string deviceInfo =
                "<DeviceInfo>" +
                "  <OutputFormat>EMF</OutputFormat>" +
                "  <PageWidth>8.5in</PageWidth>" +
                "  <PageHeight>11in</PageHeight>" +
                "  <MarginTop>0.25in</MarginTop>" +
                "  <MarginLeft>0.25in</MarginLeft>" +
                "  <MarginRight>0.25in</MarginRight>" +
                "  <MarginBottom>0.25in</MarginBottom>" +
                "</DeviceInfo>";
              Warning[] warnings;
              byte[] rpbybe = report.Render("PDF", deviceInfo, out minetype, out encod, out fextension, out streamids,
                 out warnings);
              using(FileStream fs=new FileStream("E:\\newwwfg.pdf",FileMode.Create))
              {
                  fs.Write(rpbybe , 0, rpbybe .Length);
              }
      

      }

      【讨论】:

        【解决方案6】:

        你可以实例化 LocalReport

                        FicheInscriptionBean fiche = new FicheInscriptionBean();
                        fiche.ToFicheInscriptionBean(inscription);List<FicheInscriptionBean> list = new List<FicheInscriptionBean>();
                        list.Add(fiche);
                        ReportDataSource rds = new ReportDataSource();
                        rds = new ReportDataSource("InscriptionDataSet", list);
                        // attachement du QrCode.
                        string stringToCode = numinscription + "," + inscription.Nom + "," + inscription.Prenom + "," + inscription.Cin;
                        Bitmap BitmapCaptcha = PostulerFiche.GenerateQrCode(fiche.NumInscription + ":" + fiche.Cin, Brushes.Black, Brushes.White, 200);
                        MemoryStream ms = new MemoryStream();
                        BitmapCaptcha.Save(ms, ImageFormat.Gif);
                        var base64Data = Convert.ToBase64String(ms.ToArray());
                        string QR_IMG = base64Data;
                        ReportParameter parameter = new ReportParameter("QR_IMG", QR_IMG, true);
        
                        LocalReport report = new LocalReport();
                        report.ReportPath = Page.Server.MapPath("~/rdlc/FicheInscription.rdlc");
                        report.DataSources.Clear();
                        report.SetParameters(new ReportParameter[] { parameter });
                        report.DataSources.Add(rds);
                        report.Refresh();
        
                        string FileName = "FichePreinscription_" + numinscription + ".pdf";
                        string extension;
                        string encoding;
                        string mimeType;
                        string[] streams;
                        Warning[] warnings;
                        Byte[] mybytes = report.Render("PDF", null,
                                      out extension, out encoding,
                                      out mimeType, out streams, out warnings);
                        using (FileStream fs = File.Create(Server.MapPath("~/rdlc/Reports/" + FileName)))
                        {
                            fs.Write(mybytes, 0, mybytes.Length);
                        }
                        Response.ClearHeaders();
                        Response.ClearContent();
                        Response.Buffer = true;
                        Response.Clear();
                        Response.Charset = "";
                        Response.ContentType = "application/pdf";
                        Response.AddHeader("Content-Disposition", "attachment;filename=\"" + FileName + "\"");
                        Response.WriteFile(Server.MapPath("~/rdlc/Reports/" + FileName));
        
                        Response.Flush();
                        File.Delete(Server.MapPath("~/rdlc/Reports/" + FileName));
                        Response.Close();
                        Response.End();
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-07-27
          • 2022-01-18
          • 1970-01-01
          • 2016-10-10
          • 2014-08-14
          • 1970-01-01
          • 2023-03-13
          • 1970-01-01
          相关资源
          最近更新 更多