我正在尝试执行以下操作:
- 从网页中检索生成的 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);
中提琴,我可以毫无问题地从磁盘打开文件。
为了使附件可读,我缺少什么?