我試圖做到以下幾點:腐敗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 –