【发布时间】:2011-10-28 11:22:07
【问题描述】:
我正在尝试执行以下操作:
- 从网页中检索生成的 pdf
- 创建电子邮件
- 将 pdf 附加到邮件中
- 发送消息
我能够从网页中检索 pdf 并将其作为附件发送消息。但是,当我尝试打开附件时,会收到可怕的“Adobe Reader 无法打开 'filename.pdf',因为它不是受支持的文件类型或文件已损坏”消息。
pdf 由 MVC3 页面生成,使用自定义 ActionResult 返回 pdf。看起来是这样的
public class EnrollmentExpectationsPdfResult : FileResult
{
IList<AdminRepEnrollmentExpectationViewModel> adminreps;
public EnrollmentExpectationsPdfResult(IList<AdminRepEnrollmentExpectationViewModel> adminrep)
: this("application/pdf", adminrep)
{ }
public EnrollmentExpectationsPdfResult(string contentType, IList<AdminRepEnrollmentExpectationViewModel> adminrep)
: base(contentType)
{
adminreps = adminrep;
}
protected override void WriteFile(HttpResponseBase response)
{
var cd = new ContentDisposition
{
Inline = true,
FileName = "MyPDF.pdf"
};
response.AppendHeader("Content-Disposition", cd.ToString());
//Skip a bunch of boring font stuff
...
var writer = PdfWriter.GetInstance(doc, response.OutputStream);
writer.PageEvent = new EnrollmentExpectationPDFPageEvent();
doc.Open();
//Skip the doc writing stuff
...
doc.Close();
}
}
控制器方法在这里
public ActionResult EnrollmentExpectationsPDF()
{
//skip a bunch a database stuff
...
return new EnrollmentExpectationsPdfResult(adminList);
}
这是问题核心的代码...
//Get PDF
CredentialCache cc = new CredentialCache();
cc.Add(
new Uri("http://myserver/mypdfgeneratingpage"),
"NTLM",
new NetworkCredential("myusername", "mypassword"));
var webRequestObject = (HttpWebRequest)WebRequest.Create("http://iapps.national.edu/erp/Reports/EnrollmentExpectationsPDF");
webRequestObject.Credentials = cc;
var response = webRequestObject.GetResponse();
var webStream = response.GetResponseStream();
//Create Mail
System.Net.Mail.MailMessage eMail = ...
//Skipping to attachment stuff
ContentType ct = new ContentType()
{
MediaType = MediaTypeNames.Application.Pdf,
Name = "EnrollmentExpecations_2.pdf"
};
Attachment a = new Attachment(webStream, ct);
eMail.Attachments.Add(a);
//Send Message
....
作为实验,我尝试将下载的文件写入磁盘
MemoryStream ms = new MemoryStream();
var fileStream = File.Create("C:\\MyPDF.pdf");
webStream.CopyTo(fileStream);
Viola,我可以毫无问题地从磁盘打开文件。
为了使附件可读,我缺少什么?
【问题讨论】:
-
啊...好吧,我想也许它对于电子邮件来说可能太大了。现在我必须仔细阅读代码哈哈
-
确保在发送对象后关闭并刷新流
-
@rlb.usa,这行得通......如果你把它作为答案而不是评论,我会“检查”它。谢谢!
标签: .net asp.net-mvc pdf itextsharp system.net.mail