将报告从报告查看器导出到内存流,然后通过电子邮件发送报告

时间:2015-05-11 13:11:27

标签: c# asp.net report reportviewer

我目前有一个显示本地报告的页面(在我的网页上显示报告查看器控件中的参数。我有一个要求是用户想要生成报告,然后通过按钮点击或页面加载通过电子邮件发送。我有以下代码,我曾经尝试将报告加载到内存流中然后通过电子邮件发送。电子邮件部分工作正常,但pdf没有生成。加载pdf和发送电子邮件的最佳方法是什么因为它不是这样的物理文件吗?

    WebClient client = new WebClient();
        byte[] bytes = client.DownloadData("http://localhost:51997/ReportDetails.aspx?Report1.rdlc&rs%3aFormat=PDF");

        MemoryStream ms = new MemoryStream(bytes);

        MailMessage mailObj = new MailMessage("FromAddress", "ToAddress", "header", "body text");

        SmtpClient SMTPServer = new SmtpClient("RelayServer");
        mailObj.IsBodyHtml = true;
        mailObj.Attachments.Add(new Attachment(ms, "Reports.pdf"));
        try
        {
            SMTPServer.Send(mailObj);
        }
        catch (Exception)
        {
            throw;
        }

1 个答案:

答案 0 :(得分:4)

我通过将本地报告加载到字节数组,写入文件流然后将其加载到内存流中然后发送电子邮件来解决这个问题。

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

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


        string filename = Path.Combine(Path.GetTempPath(), "Report2.rdlc");

        using (var fs = new FileStream(filename, FileMode.Create))
        {
            fs.Write(bytes, 0, bytes.Length);
            fs.Close();
        }

加载到内存流中:

MemoryStream ms = new MemoryStream(bytes);

然后作为附件发送:

  MailMessage mailObj = new MailMessage("From", "To", "header", "body");

        SmtpClient SMTPServer = new SmtpClient("relayServer");
        mailObj.IsBodyHtml = true;

        mailObj.Attachments.Add(new Attachment(ms, "report.pdf"));

        try
        {
            SMTPServer.Send(mailObj);
        }
        catch (Exception)
        {
            throw;
        }