通过web服务生成PDF,并将其作为附件通过电子邮件发送出去

本文关键字:电子邮件 服务生 web PDF 通过 | 更新日期: 2023-09-27 18:05:17

我正在尝试使用Reporting services 2005 webservice生成pdf。我有pdf生成部分工作,但我不确定如何得到一个"物理"的pdf,我可以在发送电子邮件之前附加到它。

我已经按照这个指南创建了pdf: http://www.codeproject.com/KB/reporting-services/PDFUsingSQLRepServices.aspx

public void RenderPdf(string rptMemo, string emailAddress )
{
    // Prepare Render arguments
    string historyID = null;
    string deviceInfo = null;
    string format = "PDF";
    Byte[] results;
    string encoding = String.Empty;
    string mimeType = String.Empty;
    string extension = String.Empty;
    Rse2005.Warning[] warnings = null;
    string[] streamIDs = null;
    //Credentials that will be passed to reporting services
    Rse2005.ReportExecutionService rsExec = new Rse2005.ReportExecutionService();
    rsExec.Credentials = new NetworkCredential("username", "password", "domain");
    //Report is called "Report1", it takes a parameter called "Id"
    Rse2005.ExecutionInfo ei = rsExec.LoadReport("/Reports/Report1", historyID);
    Rse2005.ParameterValue[] rptParameters = new Rse2005.ParameterValue[1];
    rptParameters[0] = new Rse2005.ParameterValue();
    rptParameters[0].Name = "Id";
    rptParameters[0].Value = RptMemo;
    //render the PDF
    rsExec.SetExecutionParameters(rptParameters, "en-us");
    results = rsExec.Render(format, deviceInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs);

    HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=DetailedQuote.pdf");
    HttpContext.Current.Response.OutputStream.Write(results, 0, results.Length);
    //This is very important if you want to directly download from stream instead of file.
    HttpContext.Current.Response.End();
}

从这一点上,我能够调用RenderPdf方法,我被提示打开/保存/取消文件。我知道如何从硬盘发送带有附件的电子邮件,但我不确定如何将结果[]转换成我可以处理的格式。

thanks in advance

通过web服务生成PDF,并将其作为附件通过电子邮件发送出去

您应该将pdf保存到磁盘或内存中,然后使用System.Net.Mail发送它这是一个来自谷歌的快速链接。http://www.systemnetmail.com/faq/3.4.2.aspx

您可以将示例中的结果写入内存流,如下所示

    var memStream = new MemoryStream(); 
    memStream.Write(results, 0 , results.Length);

你应该从你的代码中删除这3行

    HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=DetailedQuote.pdf");
    HttpContext.Current.Response.OutputStream.Write(results, 0, results.Length);
    HttpContext.Current.Response.End();

results字节数组创建MemoryStream(引用),然后将流添加到具有ContentType的附件中,并将附件添加到MailMessage上的Attachments集合中。

using (MemoryStream ms = new MemoryStream(results, 0 , results.Length, false, true))
{
    MailMessage msg = new MailMessage(...);
    ContentType ct = new ContentType()
    {
        MediaType = MediaTypeNames.Application.Octet,
        Name = "DetailedQuote.pdf"
    };
    Attachment att = new Attachment(ms, ct);
    msg.Attachments.Add(att);
}