我试图做到以下几点:腐败PDF附件
- 从网页
- 检索生成的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,我可以从磁盘上打开文件,而不会出现问题。
我为了使附件可读而错过了什么?
有多大这个PDF ? –
大概是27KB – seanicus
啊......好吧,我在想也许它对于电子邮件来说可能太大了。现在我必须阅读更接近的代码haha –